Fetching data with resolvers

GraphQL is the best way to work with data from any back-end that your product needs. It is not a mapping of your database, but rather a graph of the data sources and shapes your product is made of. Resolvers are the key to this graph. Each resolver represents a single field, and can be used to fetch data from any source(s) you may have.

Resolvers provide the instructions for turning a GraphQL operation into data. Resolvers are organized into a one to one mapping to the fields in a GraphQL schema. This section describes resolvers' organization, every field's default resolver, and their signature.

Resolver map

In order to respond to queries, a schema needs to have resolve functions for all fields. This collection of functions is called the "resolver map". This map relates the schema fields and types to a function.

With the resolver map above, the query, { author { books } }, will call the Query.author resolver first and pass its result to Author.books. The query result will contain the return value of Author.books nested under data.author.books.

Note that you don't have to put all of your resolvers in one object. Refer to the "modularizing resolvers" section to learn how to combine multiple resolver maps into one.

Resolver type signature

In addition to the parent resolvers' value, resolvers receive a couple more arguments. The full resolver function signature contains four positional arguments: (parent, args, context, info) and can return an object or Promise. Once a promise resolves, then the children resolvers will continue executing. This is useful for fetching data from a backend.

The resolver parameters generally follow this naming convention and are described in detail:

parent: The object that contains the result returned from the resolver on the parent field, or, in the case of a top-level Query field, the rootValue passed from the server configuration. This argument enables the nested nature of GraphQL queries.

args: An object with the arguments passed into the field in the query. For example, if the field was called with query{ key(arg: "you meant") }, the args object would be: { "arg": "you meant" }.

context: This is an object shared by all resolvers in a particular query, and is used to contain per-request state, including authentication information, dataloader instances, and anything else that should be taken into account when resolving the query. Read this section for an explanation of when and how to use context.

info: This argument contains information about the execution state of the query, including the field name, path to the field from the root, and more. It's only documented in the GraphQL.js source code, but is extended with additional functionality by other modules, like apollo-cache-control.

In addition to returning GraphQL defined scalars, you can return custom scalars for special use cases, such as JSON or big integers.

Resolver results

Resolvers in GraphQL can return different kinds of results which are treated differently:

null or undefined - this indicates the object could not be found. If your schema says that field is nullable, then the result will have a null value at that position. If the field is non-null, the result will "bubble up" to the nearest nullable field and that result will be set to null. This is to ensure that the API consumer never gets a null value when they were expecting a result.

An array - this is only valid if the schema indicates that the result of a field should be a list. The sub-selection of the query will run once for every item in this array.

A promise - resolvers often do asynchronous actions like fetching from a database or backend API, so they can return promises. This can be combined with arrays, so a resolver can return a promise that resolves to an array, or an array of promises, and both are handled correctly.

A scalar or object value - a resolver can also return any other kind of value, which doesn't have any special meaning but is simply passed down into any nested resolvers, as described in the next section.

Parent argument

The first argument to every resolver, parent, can be a bit confusing at first, but it makes sense when you consider what a GraphQL query looks like:

query{
getAuthor(id:5){
name
posts {
title
author {
name # this will be the same as the name above}}}}

Every GraphQL query is a tree of function calls in the server. So the parent contains the result of parent resolver, in this case:

parent in Query.getAuthor will be whatever the server configuration passed for rootValue.

parent in Author.name and Author.posts will be the result from getAuthor, likely an Author object from the backend.

parent in Post.title and Post.author will be one item from the posts result array.

parent in Author.name is the result from the above Post.author call.

Every resolver function is called according to the nesting of the query. To understand this transition from query to resolvers from another perspective, read this blog post.

Context argument

The context is how you access your shared connections and fetchers in resolvers to get data.

The context is the third argument passed to every resolver. It is useful for passing things that any resolver may need, like authentication scope, database connections, and custom fetch functions. Additionally, if you're using dataloaders to batch requests across resolvers, you can attach them to the context as well.

As a best practice, context should be the same for all resolvers, no matter the particular query or mutation, and resolvers should never modify it. This ensures consistency across resolvers, and helps increase development velocity.

To provide a context to your resolvers, add a context object to the Apollo Server constructor. This constructor gets called with every request, so you can set the context based off the details of the request (like HTTP headers).

Sending queries

Once your resolver map is complete, it's time to start testing out your queries in GraphQL Playground.

Naming operations

When sending the queries and mutations in the above examples, we've used either query { ... } or mutation { ... } respectively. While this is fine, and particularly convenient when running queries by hand, it makes sense to name the operation in order to quickly identify operations during debugging or to aggregate similar operations together for application performance metrics, for example, when using Apollo Graph Manager to monitor an API.

Operations can be named by placing an identifier after the query or mutation keyword, as we've done with HomeBookListing here:

query HomeBookListing {
getBooks {
title
}}

Queries with variables

In the examples above, we've used static strings as values for both queries and mutations. This is a great shortcut when running "one-off" operations, but GraphQL also provides the ability to pass variables as arguments and avoid the need for clients to dynamically manipulate operations at run-time.

By defining a map of variables on the root query or mutation operation, which are sent from the client, variables can be used (and re-used) within the types and fields themselves.

For example, with a slight change to the mutation we used in the previous step, we enable the client to pass title and author variables alongside the operation itself. We can also provide defaults for those variables for when they aren't explicitly set: