Skip to main content

Context

In addition to the arguments object, each resolver method/function may also access a context value. Context is the standard way to implement dependency injection for GraphQL resolvers. Typically the context value will be an object including the current request, information about the requesting user, as well as a database connection and per-request caches, such as DataLoaders.

To define the context object type, you must use the @gqlContext tag. This tag should be placed directly above the type definition for your context object.

/** @gqlContext */
type GQLCtx = {
req: Request;
userID: string;
db: Database;
};

Grats will detect any resolver parameter that is typed using the @gqlContext type and ensure that the context object is passed to the resolver in that position:

/** @gqlContext */
type GQLCtx = {
req: Request;
userID: string;
db: Database;
};

/** @gqlField */
export function me(_: Query, ctx: GQLCtx): User {
return ctx.db.users.getById(ctx.userID);
}
tip

Unlike graphql-js, Grats does not require that the context object be passed as a specific positional argument to the resolver. You can place the context object anywhere in the argument list, as long as the type is annotated with the @gqlContext type.

Constructing your context object

The mechanism by which you construct your context object will vary depending upon the GraphQL server library you are using. See your GraphQL server library's documentation for more information.

caution

Grats can ensure that every resolver is expecting the annotated context type, but it cannot ensure that the context value you construct and pass in matches that type. It is up to you to ensure that your context value is constructed correctly and passed to the GraphQL execution engine.