TExcelTAD
Home › GraphQL › How Execution Works

How Execution Works

After validation, the engine executes the query. The idea is simple: start at the root type, call a resolver for each selected field, and if the field returns an object, repeat for its sub-selection. Understanding this walk is the key to writing fast, correct GraphQL servers.

Resolvers form a tree

Every field has a resolver, a function with the signature:

js
resolve(parent, args, context, info)
Parameter Contains
parent (often called source or obj) the value returned by the parent field's resolver (the root value for top-level fields)
args the field's arguments
context an object shared by all resolvers in this request (user, loaders, db)
info details about the field, path, schema and query AST

Let's trace the order in which resolvers are called. We'll use the fieldResolver option to wrap graphql-js's default resolver with logging:

js · try it yourself
import { graphql, buildSchema, defaultFieldResolver } from 'graphql';

const schema = buildSchema(`
  type Pet { name: String, species: String }
  type Person { name: String, pets: [Pet] }
  type Query { owner: Person }
`);

const rootValue = {
  owner: {
    name: 'Sam',
    pets: [
      { name: 'Biscuit', species: 'dog' },
      { name: 'Mochi', species: 'cat' },
    ],
  },
};

const tracingResolver = (parent, args, context, info) => {
  const path = [];
  for (let p = info.path; p; p = p.prev) path.unshift(p.key);
  console.log('resolve', path.join('.'));
  return defaultFieldResolver(parent, args, context, info);
};

const result = await graphql({
  schema,
  rootValue,
  fieldResolver: tracingResolver,
  source: '{ owner { name pets { name } } }',
});
console.log(JSON.stringify(result.data));
resolve owner
resolve owner.name
resolve owner.pets
resolve owner.pets.0.name
resolve owner.pets.1.name
{"owner":{"name":"Sam","pets":[{"name":"Biscuit"},{"name":"Mochi"}]}}

The engine resolves owner, then each of its selected fields, then the fields of each pet. Fields that weren't selected (species) are never touched. The info.path includes list indexes (pets.0, pets.1).

The default resolver

When a field has no resolver of its own, graphql-js uses defaultFieldResolver. It does exactly this:

  1. Read parent[fieldName].
  2. If it's a function, call it as parent[fieldName](args, context, info) and use the result.
  3. Otherwise, return the property value.

That's why plain objects, class instances and the rootValue style all "just work". It also explains the slightly different signature you've been using in root values: ({ id }) => … receives args first, because the default resolver already knows the parent.

Promises and parallelism

Resolvers may return Promises. Sibling fields in a query are started together and awaited together, so independent slow lookups overlap:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`type Query { weather: String, news: String, stocks: String }`);

const log = [];
const slow = (name, ms) => () =>
  new Promise((resolve) => {
    log.push(`start ${name}`);
    setTimeout(() => {
      log.push(`end ${name}`);
      resolve(`${name} ready`);
    }, ms);
  });

const rootValue = { weather: slow('weather', 30), news: slow('news', 10), stocks: slow('stocks', 20) };

const result = await graphql({ schema, rootValue, source: '{ weather news stocks }' });
console.log(log.join('\n'));
console.log(JSON.stringify(result.data));
start weather
start news
start stocks
end news
end stocks
end weather
{"weather":"weather ready","news":"news ready","stocks":"stocks ready"}

All three started before any finished, and they ended in order of speed. The response still lists fields in query order. (Remember from the Mutations lesson: top-level mutation fields are the exception and run one after another.)

Completing values

After a resolver returns, the engine completes the value according to the field's type:

Field type Completion
scalar / enum serialize (e.g. 7.0 → 7, number → "42" for ID)
object resolve the sub-selection with this value as parent
list complete every item
interface / union find the concrete type, then resolve as an object
non-null check the value isn't null (otherwise: error + propagation)

Seeing it all: a parent-aware resolver

Because each resolver receives its parent, nested fields can compute values from the object above them. Here Order.total is derived from its lines:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  type Line { product: String!, qty: Int!, unitPrice: Int! }
  type Order { id: ID!, lines: [Line!]!, total: Int! }
  type Query { order: Order }
`);

const rootValue = {
  order: {
    id: 'ORD-7',
    lines: [
      { product: 'Notebook', qty: 3, unitPrice: 4 },
      { product: 'Pen', qty: 10, unitPrice: 1 },
    ],
    // `this` is the parent object: the order.
    total() {
      return this.lines.reduce((sum, l) => sum + l.qty * l.unitPrice, 0);
    },
  },
};

const result = await graphql({ schema, rootValue, source: '{ order { id total } }' });
console.log(JSON.stringify(result.data));
{"order":{"id":"ORD-7","total":22}}

Test yourself

What is the first argument a field resolver receives?

  1. The arguments
  2. The parent value
  3. The context
  4. The schema

What does the default field resolver do when parent[fieldName] is a function?

  1. Returns the function
  2. Calls it with (args, context, info)
  3. Throws an error
  4. Returns null

How are sibling fields of a query resolved when they return Promises?

  1. Strictly one after another
  2. Started together and awaited together
  3. Only the first one runs
  4. In alphabetical order