Skip to content

Resolving Queries ​

The examples on this page use the UserModel and PostModel models from Relations.

Resolve a list or a single object ​

Pass the query that selects the rows to graph.resolve and return its result:

ts
const resolvers = {
  Query: {
    posts: (_parent, _args, context, info) => {
      return graph.resolve(PostModel.query().orderBy("id"), { context, info })
    },
    user: (_parent, { id }, context, info) => {
      return graph.resolve(UserModel.query().findById(id), { context, info })
    },
  },
}

The graph keeps everything the query already has, such as conditions, order, and limits, and adds the columns and relations that the client selected. The result type follows the query: a list for PostModel.query(), and a single object or undefined for findById.

Return the result of a mutation ​

Write the data first, then resolve a query that reads it back. This example assumes that create_post takes text and author_id:

ts
const resolvers = {
  Mutation: {
    async create_post(_parent, args, context, info) {
      const post = await PostModel.query().insert(args)
      return graph.resolve(post.$query(), { context, info })
    },
  },
}

Resolve an object nested in the result ​

When a root field returns an object that only partly comes from the database, such as a login result with a token and the user, resolve the database part with path:

gql
type LoginResult {
  token: String!
  user: User!
}

type Mutation {
  login(email: String!, password: String!): LoginResult!
}
ts
const resolvers = {
  Mutation: {
    async login(_parent, args, context, info) {
      // Your own authentication.
      const { token, userId } = await authenticate(args)
      return {
        token,
        user: await graph.resolve(UserModel.query().findById(userId), {
          context,
          info,
          path: ["user"],
        }),
      }
    },
  },
}

path lists the GraphQL fields from the root field down to the object to resolve. When the client does not select user, graph.resolve runs no query and returns undefined.

Currently broken

When the client selects the field under an alias, such as member: user { id }, graph.resolve returns undefined instead of the user.

Register the types ​

Register in r.graph every GraphQL type whose objects your models load: the types of root queries, of relations, and of page nodes. Do not register wrapper types that your own resolvers build, such as LoginResult above or the page types from Pagination.

Type the context ​

Pass the type of your GraphQL context to r.graph to type context in the callbacks of the graph, such as modify and transform:

ts
interface Context {
  userId?: number
  isAdmin?: boolean
}

const graph = r.graph<Context>({
  User: r.model(UserModel),
  Post: r.model(PostModel),
})

In the transform callback of r.model, use transform(instance, { context }) to access that GraphQL context.