You are viewing the preview version of this book
Click here for the full version.

Context

The context contains the input for the template. It is passed to the resolver code as the first argument of the request/response functions. What values are present depends on the GraphQL query, whether it is for a request or a response mapping template, and whether it's a pipeline or a unit resolver.

The reference contains an up-to-date list of the available values in the context. Here, we are going to discuss these values briefly.

arguments

The ctx.arguments, or ctx.args for short, contains the arguments for the field being resolved. For example, in this query:

query Query1 {
  user(username: "user1") {
    username
    tickets(after: 1639907490) {
      text
      created
    }
  }
}

The ctx.args contains a username for the Query.user and an after for the User.tickets resolver.

Arguments are defined only for the direct resolver of the field

source

The ctx.source contains the result of the parent field and is only defined for nested fields. The source provides a way to pass data down the object hierarchy until only leaf nodes remain.

For example, the query contains two levels of nesting:

query Query1 {
  user(username: "user1") {
    username
    tickets(after: 1639907490) {
      text
      created
    }
  }
}

First, the Query.user resolver will run, where the ctx.source is undefined. Then the User.username runs, where the source is the result of the Query.user. The same happens with User.tickets. Then the Ticket.text and the Ticket.created resolvers run, both getting one object from the result of the User.tickets.

Source object in nested resolvers

identity

Try it yourself

You can find code example for this chapter here.

There is more, but you've reached the end of this preview
Read this and all other chapters in full and get lifetime access to:
  • all future updates
  • full web-based access
  • PDF and Epub versions