In the Bookshop warehouse, one order is handled as a chain. The first clerk takes the book off the shelf and hands it to a second clerk, who looks up its author and hands that to a third clerk, who finds the author's other books. Each clerk starts from what the previous one handed over.
On a GraphQL server, each of those clerks is a resolver: a function that fills in the value of one field. The schema only says which fields exist; the resolver finds what goes in them, from a database for instance. That chain of clerks is a resolver chain.
Four parameters: parent, args, context, info
This is part of the Bookshop resolvers, exactly what the Lab on this page runs:
const resolvers = {
Query: {
book: (_, args) => books.find((b) => String(b.id) === args.id) ?? fail("Book not found"),
},
Book: {
status: (book) => statusOf(book),
author: (book) => authors.find((a) => a.id === book.authorId),
},
Author: {
books: (author) => books.filter((b) => b.authorId === author.id),
},
};
- Resolvers are grouped by type, then by field:
Book.authoris the resolver of theauthorfield on the typeBook. - Every resolver is called with four parameters, always in this order:
(parent, args, context, info). The ones you don't use may be left out, or named_.
| Parameter | What it holds | Example |
|---|---|---|
parent |
the result of the resolver one level up | in Book.author: the book row { id: 1, title: "The Rainbow Troops", authorId: 1, price: 89000, stock: 12 } |
args |
this field's arguments, already type-checked | in Query.book: { id: "1" }, a string because its type is ID |
context |
an object shared by one request | { user, db } |
info |
facts about the field being filled | info.fieldName = "author", info.path = book, then author |
On a top-level field (Query.book), parent is the root value, usually undefined. That's why it's written _.
The resolver chain: book → author → books
{
book(id: 1) {
title
author {
name
books {
title
}
}
}
}
The GraphQL engine works from the top down. Each resolver's result becomes the parent of the fields inside it:
| # | Field | parent it gets |
Resolver | Its result |
|---|---|---|---|---|
| 1 | Query.book |
undefined, args { id: "1" } |
written by us | the row of book 1 |
| 2 | Book.title |
the row of book 1 | default | "The Rainbow Troops" |
| 3 | Book.author |
the row of book 1 | written by us | { id: 1, name: "Andrea Hirata" } |
| 4 | Author.name |
author 1 | default | "Andrea Hirata" |
| 5 | Author.books |
author 1 | written by us | a list holding book 1 |
| 6 | Book.title |
the row of book 1 | default | "The Rainbow Troops" |
Six calls: three resolvers we wrote, three default ones. The response is { "book": { "title": "The Rainbow Troops", "author": { "name": "Andrea Hirata", "books": [{ "title": "The Rainbow Troops" }] } } }.
The default resolver: reading a property
A field with no resolver still gets a value, because graphql-js uses a default resolver: it reads the property of the same name from parent (parent.title), and calls it if that property is a function. That's why title, price, stock and name need no resolver.
Book.author is different. The book row stores authorId, not author. Before reading on, guess: if the Book.author resolver is removed, what does the query { book(id: 1) { title author { name } } } answer?
Without that resolver, the default one reads book.author, which is undefined, and author, typed Author!, may not be empty:
{
"errors": [
{
"message": "Cannot return null for non-nullable field Book.author.",
"locations": [{ "line": 4, "column": 5 }],
"path": ["book", "author"]
}
],
"data": { "book": null }
}
The null from author moves up to the nearest place that may be null, which is book. So even the title is gone. When a resolver throws in a non-null field, the null moves up the same way; only the message is that error's. The rule: write a resolver for a field whose value isn't sitting in parent as it is (a relation like author, a computed value like status), and leave the rest to the default.
Async resolvers
A real resolver usually reads a database, so it's async and returns a Promise. graphql-js waits for that Promise before filling in the fields below it:
const resolvers = {
Query: {
books: async (_, args, context) => context.db.books.findMany(),
},
Book: {
author: async (book, _, context) => context.db.authors.findById(book.authorId),
},
};
There's one effect worth knowing. For { books { title author { name } } }, the engine doesn't wait for one book to finish before starting the next. With async resolvers the calls come in this order: Query.books, then Book.title and Book.author for books 1, 2 and 3, and only then Author.name three times, once all three authors have arrived. Book.author is called three times, once per book. If each call is one database query, that's the N+1 problem, covered in the "N+1 Problem & DataLoader" lesson. A mutation's top-level fields still run in order, even when their resolvers are async.
context: made fresh for each request
The server makes context once per request, then hands it to every resolver of that request. In Apollo Server:
const { url } = await startStandaloneServer(server, {
context: async ({ req }) => ({
user: await userFromToken(req.headers.authorization),
db,
}),
});
- It holds what many resolvers need: the logged-in user, the database connection, a cache for one request.
- It's made fresh for each request because each request may come from a different user. Never keep a user's data in a global variable, or it leaks into someone else's request.
- How
context.useris filled from a token is covered in the "Authentication & Authorization" lesson.
Business logic outside the resolvers
A resolver is best kept thin: read args and context, call a business function, return its result. A rule like "stock can't be negative" belongs in that function, for instance updateStock: (_, { id, stock }, { services }) => services.stock.update(id, stock). Then the same rule serves the REST API, scheduled jobs and tests too, without being written again.
⚠️ Four ways a resolver causes trouble
- A relation field with no resolver.
authoris read frombook.author, which isn't there, so it'snull, and thenCannot return null for non-nullable field Book.author. - A missing
return. A resolver with braces and noreturnreturnsundefined, which counts asnull. - Parameters in the wrong order. The arguments are the second parameter:
(_, args), not(args). On a top-level field the first parameter is the root value. - Keeping request data in a global variable. The user, their permissions and per-request caches go in
context.
TL;DR: A resolver is a function that fetches the data for each field in the schema, grouped by type and field (Book.author). Its parameters are always (parent, args, context, info): the result of the resolver above it, the field's arguments, an object shared by one request, and facts about the field. Resolvers chain: Query.book returns a book row, which becomes the parent of Book.author, whose result becomes the parent of Author.books. A field with no resolver uses the default one, which reads parent[fieldName]; a relation field like author needs its own, and without it a null in a non-null field moves up to the nearest place that may be null. Resolvers may be async; siblings start without waiting for each other. context is made fresh for each request, and business logic is best kept outside the resolvers.
⚡ One function per field
Write:
const resolvers = {
Book: {
author: (book) => authors.find((a) => a.id === book.authorId),
},
};
Meaning: Resolvers are grouped by type, then by field: this is Book.author. Its parameters always come in this order: (parent, args, context, info). Here parent is the book row from the resolver above it.
⚡ The chain: book, then author
Meaning: For { book(id: 1) { title author { name } } }, the result of Query.book becomes the parent of Book.author, and the result of Book.author becomes the parent of Author.name. In Query.book, parent is usually undefined, which is why it's written _.
⚡ The default resolver
Guess first: the Book.author resolver is removed. What does the query { book(id: 1) { title author { name } } } answer?
"data": { "book": null } with the error Cannot return null for non-nullable field Book.author. The book row only has authorId, so author is undefined, and its null moves up to book. Even the title is gone.
Meaning: A field with no resolver reads the property of the same name from parent. That's enough for title and name, but a relation like author needs a resolver of its own.