Resolvers

Beginner · 10 min

A resolver produces one field's value. See how execution walks the query, why default resolvers cover most fields, and how Query.post leads to Post.author.

Before thisObject types and fieldsFields and selection setsMutations

Net Ninja · 10 min

Resolvers

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Net NinjaReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A resolver is a function attached to one field of one type, written `resolvers.Type.field`, that returns that field's value.
  • Execution starts at a root field, resolves it, then resolves each selected subfield with the returned object as the `parent`; only resolvers for selected fields run.
  • A field without a resolver uses the default one, which reads `parent[fieldName]` and calls it if it is a function, so rows that already contain the data need no resolver.
  • A resolver can return a value or a promise; the executor waits for promises before continuing down the tree.
  • Put a resolver on a field when its value needs a lookup, a computation or a rename that the parent object does not already carry.

The problem: a schema describes shape, not behaviour

The SDL says that a Post has a title and an author. It says nothing about where those come from: a database, another service, a computation. Something has to bridge the type system to your data, and that bridge is the resolver.

A resolver is a function that returns the value of one field. The schema is the menu; resolvers are the kitchen stations. A request does not call one big handler. The executor walks the query and asks the right station for each piece.

The resolver map

Resolvers sit in an object keyed by type name and then field name:

const resolvers = {
  Query: {
    post: (_parent, { id }, { db }) =>
      db.prepare('SELECT * FROM posts WHERE id = ?').get(id) ?? null,
  },
  Post: {
    author: (post, _args, { db }) =>
      db.prepare('SELECT * FROM authors WHERE id = ?').get(post.author_id),
  },
  Author: {
    postCount: (author, _args, { db }) =>
      db.prepare('SELECT COUNT(*) AS c FROM posts WHERE author_id = ?').get(author.id).c,
  },
};

Query.post is a root resolver. Post.author runs after Query.post, and its first argument, post, is whatever Query.post returned. The shape of the code mirrors the shape of the schema. The full list of what a resolver receives is in context and resolver arguments.

Execution walks the tree

I ran this against Yoga 6.1.0 and SQLite, with a counter that records every resolver call. Three queries, three different sets of calls:

{ post(id:"1") { title } }
  resolvers run: Query.post

{ post(id:"1") { title author { name } } }
  resolvers run: Query.post, Post.author

{ post(id:"1") { author { name postCount } } }
  resolvers run: Query.post, Post.author, Author.postCount

Only the fields a client selects are resolved. A field that exists in the schema but is not in the query costs nothing. That is why a GraphQL server can expose an expensive field such as postCount without penalizing every client: it is paid for by whoever asks.

The tree is resolved top to bottom, and siblings can resolve in parallel (apart from mutation fields, as covered in mutations).

The default resolver

Notice that nothing resolves Post.title above. A field with no resolver uses the default: it takes parent[fieldName], and if that property is a function, it calls it with (args, context, info). With plain graphql-js:

const schema = buildSchema(`type Query { hello(name: String = "you"): String! plain: String! }`);
await graphql({
  schema,
  source: '{ hello(name: "Ada") plain }',
  rootValue: {
    hello: (args, ctx, info) => `Hi ${args.name} from ${info.fieldName}`,
    plain: 'a value',
  },
});
// { data: { hello: "Hi Ada from hello", plain: "a value" } }

So a row { id, title, author_id } already answers id and title. You write a resolver only when the parent lacks the data (author), when the name differs (Post.authorId from author_id), or when a field is computed.

If the property is missing, the default returns undefined, which GraphQL reads as null. On a non-null field that is an error. The classic bug is a schema field createdAt while the row column is created_at; the resolver for that field has to bridge the two.

Resolvers may be async

A resolver can return a value or a promise. The executor waits for it before moving to the children. That is how a database call fits in: return the promise from the driver. A resolver may also throw; what happens then is the subject of errors and partial responses. If promises are new to you, see promises.

Keep resolvers thin

A resolver should translate between GraphQL and your application, not contain it. Business rules such as “only the author can delete a post” belong in a service layer that resolvers call. The same service then works from a job, a script, or a test, and swapping GraphQL out for another transport does not mean rewriting your rules. A resolver body that grows past a few lines is usually a service function waiting to be extracted.

The small, repeated shape also has a cost: every Post.author resolver is a separate lookup, and a list of ten posts runs it ten times. That is the N+1 problem, two lessons ahead.

What the video covers

Net Ninja’s crash course episode 5, “Resolver Functions,” is a ten-minute video from 2023 using Apollo Server. Its description lists only course links and the Apollo docs, so this lesson rests on the title: it writes resolver functions for its schema. Apollo Server and Yoga both take the same resolver map, so the shape transfers. The tracing of which resolvers run and the default resolver are this lesson’s additions.

Where this fits

You know what a resolver is and what it receives first, parent. The other arguments, especially the shared context, decide how clean your server turns out. Next: context and resolver arguments.

Check yourself

  1. 01If a query selects only `post { title }`, which resolvers run?

    Only `Query.post`. `Post.title` falls back to the default resolver reading `parent.title`, and fields such as `Post.author` that were not selected never run.

  2. 02What does the default resolver do when the parent has no matching property?

    It returns `undefined`, which GraphQL treats as null. On a non-null field that becomes an error, so you add a resolver for fields the parent object does not carry.

  3. 03Why does the schema define `Post.author` as a field when the posts table only has an `author_id` column?

    The schema describes the shape clients want, not the storage. A `Post.author` resolver reads `author_id` from the parent and loads the author.

  4. 04In what order do `Query.post` and `Post.author` resolve for `{ post { author { name } } }`?

    `Query.post` first. Its return value becomes the parent of `Post.author`, whose return value becomes the parent of `Author.name`.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark