Apollo Server 2 is officially end-of-life as of 22 October 2023.

Learn more about upgrading.

Resolvers

How Apollo Server processes GraphQL operations


Apollo Server needs to know how to populate data for every field in your schema so that it can respond to requests for that data. To accomplish this, it uses resolvers.

A resolver is a function that's responsible for populating the data for a single field in your schema. It can populate that data in any way you define, such as by fetching data from a back-end database or a third-party API.

If you don't define a resolver for a particular field, Apollo Server automatically defines a default resolver for it.

Defining a resolver

Base syntax

Let's say our server defines the following (very short) schema:

GraphQL
1type Query {
2  numberSix: Int! # Should always return the number 6 when queried
3  numberSeven: Int! # Should always return 7
4}

We want to define resolvers for the numberSix and numberSeven fields of the root Query type so that they always return 6 and 7 when they're queried.

Those resolver definitions look like this:

JavaScript
1const resolvers = {
2  Query: {
3    numberSix() {
4      return 6;
5    },
6    numberSeven() {
7      return 7;
8    }
9  }
10};

As this example shows:

  • You define all of your server's resolvers in a single JavaScript object (named resolvers above). This object is called the resolver map.

  • The resolver map has top-level fields that correspond to your schema's types (such as Query above).

  • Each resolver function belongs to whichever type its corresponding field belongs to.

Handling arguments

Now let's say our server defines the following (slightly longer) schema:

GraphQL
1type User {
2  id: ID!
3  name: String
4}
5
6type Query {
7  user(id: ID!): User
8}

We want to be able to query the user field to fetch a user by its id.

To achieve this, our server needs access to user data. For this contrived example, assume our server defines the following hardcoded array:

JavaScript
1const users = [
2  {
3    id: '1',
4    name: 'Elizabeth Bennet'
5  },
6  {
7    id: '2',
8    name: 'Fitzwilliam Darcy'
9  }
10];

To learn how to fetch data from an external source (like a database or REST API), see Data sources.

Now we can define a resolver for the user field, like so:

JavaScript
1const resolvers = {
2  Query: {
3    user(parent, args, context, info) {
4      return users.find(user => user.id === args.id);
5    }
6  }
7}

As this example shows:

  • A resolver can optionally accept four positional arguments: (parent, args, context, info).

    Learn more about these arguments

  • The args argument is an object that contains all GraphQL arguments that were provided for the field by the GraphQL operation.

Notice that this example doesn't define resolvers for User fields (id and name). That's because the default resolver that Apollo Server creates for each of these fields does the right thing: it obtains the value directly from the object returned by the user resolver.

Passing resolvers to Apollo Server

After you define all of your resolvers, you pass them to the constructor of ApolloServer (as the resolvers property), along with your schema's definition (as the typeDefs property).

The following example defines a hardcoded data set, a schema, and a resolver map. It then initializes an ApolloServer instance, passing the schema and resolvers to it.

Expand example
JavaScript
1const { ApolloServer, gql } = require('apollo-server');
2
3// Hardcoded data store
4const books = [
5  {
6    title: 'The Awakening',
7    author: 'Kate Chopin',
8  },
9  {
10    title: 'City of Glass',
11    author: 'Paul Auster',
12  },
13];
14
15// Schema definition
16const typeDefs = gql`
17  type Book {
18    title: String
19    author: String
20  }
21
22  type Query {
23    books: [Book]
24  }
25`;
26
27// Resolver map
28const resolvers = {
29  Query: {
30    books() {
31      return books;
32    }
33  },
34};
35
36// Pass schema definition and resolvers to the
37// ApolloServer constructor
38const server = new ApolloServer({ typeDefs, resolvers });
39
40// Launch the server
41server.listen().then(({ url }) => {
42  console.log(`🚀  Server ready at ${url}`);
43});

Note that you can define your resolvers across as many different files and objects as you want, as long as you merge all of them into a single resolver map that's passed to the ApolloServer constructor.

Resolver chains

Whenever a query asks for a field that contains an object type, the query also asks for at least one field of that object (if it didn't, there would be no reason to include the object in the query). A query always "bottoms out" on fields that contain either a scalar or a list of scalars.

Therefore, whenever Apollo Server resolves a field that contains an object type, it always then resolves one or more fields of that object. Those subfields might in turn also contain object types. Depending on your schema, this object-field pattern can continue to an arbitrary depth, creating what's called a resolver chain.

Example

Let's say our server defines the following schema:

GraphQL
1# A library has a branch and books
2type Library {
3  branch: String!
4  books: [Book!]
5}
6
7# A book has a title and author
8type Book {
9  title: String!
10  author: Author!
11}
12
13# An author has a name
14type Author {
15  name: String!
16}
17
18type Query {
19  libraries: [Library]
20}

Here's a valid query against that schema:

GraphQL
1query GetBooksByLibrary {
2  libraries {
3    books {
4      author {
5        name
6      }
7    }
8  }
9}

The resulting resolver chain for this query matches the hierarchical structure of the query itself:

These resolvers execute in the order shown above, passing their return value to the next resolver in the chain via the parent argument.

Here's a code sample that can resolve the query above with this resolver chain:

Expand example
JavaScript
1const { ApolloServer, gql } = require('apollo-server');
2
3const libraries = [
4  {
5    branch: 'downtown'
6  },
7  {
8    branch: 'riverside'
9  },
10];
11
12// The branch field of a book indicates which library has it in stock
13const books = [
14  {
15    title: 'The Awakening',
16    author: 'Kate Chopin',
17    branch: 'riverside'
18  },
19  {
20    title: 'City of Glass',
21    author: 'Paul Auster',
22    branch: 'downtown'
23  },
24];
25
26// Schema definition
27const typeDefs = gql`
28
29# A library has a branch and books
30  type Library {
31    branch: String!
32    books: [Book!]
33  }
34
35  # A book has a title and author
36  type Book {
37    title: String!
38    author: Author!
39  }
40
41  # An author has a name
42  type Author {
43    name: String!
44  }
45
46  # Queries can fetch a list of libraries
47  type Query {
48    libraries: [Library]
49  }
50`;
51
52// Resolver map
53const resolvers = {
54  Query: {
55    libraries() {
56
57      // Return our hardcoded array of libraries
58      return libraries;
59    }
60  },
61  Library: {
62    books(parent) {
63
64      // Filter the hardcoded array of books to only include
65      // books that are located at the correct branch
66      return books.filter(book => book.branch === parent.branch);
67    }
68  },
69  Book: {
70
71    // The parent resolver (Library.books) returns an object with the
72    // author's name in the "author" field. Return a JSON object containing
73    // the name, because this field expects an object.
74    author(parent) {
75      return {
76        name: parent.author
77      };
78    }
79  }
80
81  // Because Book.author returns an object with a "name" field,
82  // Apollo Server's default resolver for Author.name will work.
83  // We don't need to define one.
84};
85
86// Pass schema definition and resolvers to the
87// ApolloServer constructor
88const server = new ApolloServer({ typeDefs, resolvers });
89
90// Launch the server
91server.listen().then(({ url }) => {
92  console.log(`🚀  Server ready at ${url}`);
93});

If we now update our query to also ask for each book's title:

GraphQL
1query GetBooksByLibrary {
2  libraries {
3    books {
4      title
5      author {
6        name
7      }
8    }
9  }
10}

Then the resolver chain looks like this:

When a chain "diverges" like this, each subchain executes in parallel.

Resolver arguments

Resolver functions are passed four arguments: parent, args, context, and info (in that order).

You can use any name for each argument in your code, but the Apollo docs use these names as a convention. Instead of parent, it's also common to use the parent type's name or source.

ArgumentDescription
parent

The return value of the resolver for this field's parent (i.e., the previous resolver in the resolver chain).

For resolvers of top-level fields with no parent (such as fields of Query), this value is obtained from the rootValue function passed to Apollo Server's constructor.

args

An object that contains all GraphQL arguments provided for this field.

For example, when executing query{ user(id: "4") }, the args object passed to the user resolver is { "id": "4" }.

context

An object shared across all resolvers that are executing for a particular operation. Use this to share per-operation state, including authentication information, dataloader instances, and anything else to track across resolvers.

See The context argument for more information.

info

Contains information about the operation's execution state, including the field name, the path to the field from the root, and more.

Its core fields are listed in the GraphQL.js source code, and it is extended with additional functionality by other modules, like apollo-cache-control.

The context argument

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

Resolvers should never destructively modify the context argument. This ensures consistency across all resolvers and prevents unexpected errors.

To provide a context to your resolvers, add a context initialization function to the ApolloServer constructor. This function is called with every request, so you can set the context based on the request's details (such as HTTP headers).

JavaScript
1
2// Constructor
3const server = new ApolloServer({
4  typeDefs,
5  resolvers,
6  context: ({ req }) => ({
7    authScope: getScope(req.headers.authorization)
8  })
9}));
10
11// Example resolver
12(parent, args, context, info) => {
13  if(context.authScope !== ADMIN) throw new AuthenticationError('not admin');
14  // Proceed
15}

The fields of the object passed to your context function differ if you're using middleware besides Express. See the API reference for details.

Context initialization can be asynchronous, allowing database connections and other operations to complete:

JavaScript
1context: async () => ({
2  db: await client.connect(),
3})
4
5// Resolver
6(parent, args, context, info) => {
7  return context.db.query('SELECT * FROM table_name');
8}

Return values

A resolver function's return value is treated differently by Apollo Server depending on its type:

TypeDescription
Scalar / object

A resolver can return a single value or an object, as shown in Defining a resolver. This return value is passed down to any nested resolvers via the parent argument.

Array

Return an array if and only if your schema indicates that the resolver's associated field contains a list.

After you return an array, Apollo Server executes nested resolvers for each item in the array.

null / undefined

Indicates that the value for the field could not be found.

If your schema indicates that this resolver's field is nullable, then the operation result has a null value at the field's position.

If this resolver's field is not nullable, Apollo Server sets the field's parent to null. If necessary, this process continues up the resolver chain until it reaches a field that is nullable. This ensures that a response never includes a null value for a non-nullable field.

Promise

Resolvers often perform asynchronous actions, such as fetching from a database or back-end API. To support this, a resolver can return a promise that resolves to any other supported return type.

Default resolvers

If you don't define a resolver for a particular schema field, Apollo Server defines a default resolver for it (see the source).

The default resolver function uses the following logic:

As an example, consider the following schema excerpt:

GraphQL
1type Book {
2  title: String
3}
4
5type Author {
6  books: [Book]
7}

If the resolver for the books field returns an array of objects that each contain a title field, then you can use a default resolver for the title field. The default resolver will correctly return parent.title.

Monitoring resolver performance

As with all code, a resolver's performance depends on its logic. It's important to understand which of your schema's fields are computationally expensive or otherwise slow to resolve, so that you can either improve their performance or make sure you only query them when necessary.

Apollo Studio integrates directly with Apollo Server to provide field-level metrics that help you understand the performance of your data graph over time. For more information, see Analyzing performance.

While developing locally, you can provide tracing: true to the ApolloServer constructor to enable a tracing panel:

JavaScript
1const server = new ApolloServer({
2  typeDefs,
3  resolvers,
4  tracing: true,
5});
Feedback

Edit on GitHub

Forums