'What does GraphQL do with the return value from a resolver?
I recently started learning GraphQL and I've discovered a situation that I'm unable to explain.
Take the following example
var {ApolloServer, gql} = require("apollo-server")
const typeDefs = gql`
type Query {
test: type1!
}
type type1 {
value: String!
}
`;
const resolvers = {
Query: {
test: (parent) => {
console.log(parent)
return "How does my query still work?!"
}
},
type1: {
value: (parent) => {
console.log(parent)
return "hello!"
}
}
}
const server = new ApolloServer({ typeDefs, resolvers })
server.listen(8080).then(({url}) => console.log(`server stated on ${url}`))
Under normal circumstances, GraphQL resolves the a query from the outside to the inside and will use the most specific resolver it has for a given field until all fields have been resolved.
What I find perplexing about this example is what exactly happens to the string that I return from my top level resolver.
This query
query {
test {
value
}
}
yields the result
{
"data": {
"test": {
"value": "hello!"
}
}
}
Given the above example, I would fully expect my GraphQL server to throw an error since my top level resolver returns a String
instead of the type1
that the schema asks for.
My question is basically, what is my server doing with the values that my resolvers return? Clearly, if I return a String
in my top level resolver, something pretty big must be happening for that to translate into an Object
for the query response.
Solution 1:[1]
I encountered the same thing today. I didn't understand what's the need for providing a return type if you can return anything like a string for a specific type definition?
So if I see how REST API is done then I can think that the return type is for API documentation and for the application that is consuming it which is hinted in the HTTP content-type header. This tells you an example the return type is of type 'application/json' but not the schema - maybe there is a different header for it? or the application can get it from some kind of API documentation like Swagger.
Useful Swagger doc snippet from https://swagger.io/docs/specification/describing-responses/
paths:
/users:
get:
summary: Get all users
responses:
'200':
description: A list of users
content:
application/json:
schema:
$ref: '#/components/schemas/ArrayOfUsers'
application/xml:
schema:
$ref: '#/components/schemas/ArrayOfUsers'
text/plain:
schema:
type: string
PS: Very new to the web domain. Kindly let me know of any incorrect assumptions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nishit Shetty |