HomeAbout

Fields

Lifecycle of GraphQL Request

How Query gets parsed

Queries are parsed, validated and executed.

A query is first parsed into an abstract syntax tree (or AST).

The AST is validated against the schema. Checks for correct query syntax and if the fields exist.

The runtime walks through the AST, starting from the root of the tree, invokes resolvers, collects up results, and emits JSON.

Execution

After being validated, a GraphQL query is executed by a GraphQL server which returns a result that mirrors the shape of the requested query, typically as JSON.

GraphQL cannot execute a query without a type system.

At the top level of every GraphQL server is a type that represents all the possible entry points into the GraphQL API, it’s often called the Root type or the Query type.

# root query type Query { # root field person(id: ID!): Person } # root mutation type Mutation { # ... }

Query Execution

The tree is executed breadth-first, meaning user must be resolved before its children name and email are executed.

Root Query fields, like user and album, are executed in parallel but in no particular order.

If the user resolver is asynchronous, the user branch delays until its resolved. Once all leaf nodes, name, email, title, are resolved, execution is complete.

How Apollo maps the Schema to a Resolver

Apollo maps the schema to a resolver by matching based on field names.

  • Apollo looks for resolver field in an object that mirrors the structure of the schema.

Apollo also uses type matching.

  • Apollo matches resolvers to types by checking for an object in the resolvers structure that corresponds to each type name (Query, User, etc.).
type Query { user(id: ID!): User } type User { id: ID! name: String email: String }
// corresponding resolvers const resolvers = { Query: { user: (parent, args, context) => { /* resolve user by ID */ }, }, User: { name: (parent) => parent.name, email: (parent) => parent.email, }, };

Query Execution Order

Three high level steps:

  • parse
  • validate
  • execute

Execution Steps

  1. Parsing the query
  • First, the server parses the string and turns it into an AST — an abstract syntax tree. If there are any syntax errors, the server will stop execution and return the syntax error to the client.
  1. Validation
  • A query can be syntactically correct, but still make no sense.
  • The validation stage makes sure that the query is valid given the schema before execution starts.
  1. Execution
AboutContact