Resolvers

Resolvers provide the instructions for turning a GraphQL operation (a query, mutation, or subscription) into data. They return the same shape of data we specify in our schema — either synchronously or as a promise that resolves to a result of that shape. Typically, you create a resolver map manually. The @nestjs/graphql package, on the other hand, generates a resolver map automatically using the metadata provided by decorators you use to annotate classes. To demonstrate the process of using the package features to create a GraphQL API, we’ll create a simple authors API.

Code first

In the code first approach, we don’t follow the typical process of creating our GraphQL schema by writing GraphQL SDL by hand. Instead, we use TypeScript decorators to generate the SDL from TypeScript class definitions. The @nestjs/graphql package reads the metadata defined through the decorators and automatically generates the schema for you.

Object types

Most of the definitions in a GraphQL schema are object types. Each object type you define should represent a domain object that an application client might need to interact with. For example, our sample API needs to be able to fetch a list of authors and their posts, so we should define the Author type and Post type to support this functionality.

If we were using the schema first approach, we’d define such a schema with SDL like this:

  1. type Author {
  2. id: Int!
  3. firstName: String
  4. lastName: String
  5. posts: [Post]
  6. }

In this case, using the code first approach, we define schemas using TypeScript classes and using TypeScript decorators to annotate the fields of those classes. The equivalent of the above SDL in the code first approach is:

authors/models/author.model.ts

  1. import { Field, Int, ObjectType } from '@nestjs/graphql';
  2. import { Post } from './post';
  3. @ObjectType()
  4. export class Author {
  5. @Field(type => Int)
  6. id: number;
  7. @Field({ nullable: true })
  8. firstName?: string;
  9. @Field({ nullable: true })
  10. lastName?: string;
  11. @Field(type => [Post])
  12. posts: Post[];
  13. }

Hint TypeScript’s metadata reflection system has several limitations which make it impossible, for instance, to determine what properties a class consists of or recognize whether a given property is optional or required. Because of these limitations, we must either explicitly use the @Field() decorator in our schema definition classes to provide metadata about each field’s GraphQL type and optionality, or use a CLI plugin to generate these for us.

The Author object type, like any class, is made of a collection of fields, with each field declaring a type. A field’s type corresponds to a GraphQL type. A field’s GraphQL type can be either another object type or a scalar type. A GraphQL scalar type is a primitive (like ID, String, Boolean, or Int) that resolves to a single value.

Hint In addition to GraphQL’s built-in scalar types, you can define custom scalar types (read more).

The above Author object type definition will cause Nest to generate the SDL we showed above:

  1. type Author {
  2. id: Int!
  3. firstName: String
  4. lastName: String
  5. posts: [Post]
  6. }

The @Field() decorator accepts an optional type function (e.g., type => Int), and optionally an options object.

The type function is required when there’s the potential for ambiguity between the TypeScript type system and the GraphQL type system. Specifically: it is not required for string and boolean types; it is required for arrays, numbers (which must be mapped to either a GraphQL Int or Float) and object types. The type function should simply return the desired GraphQL type (as shown in various examples in these chapters).

The options object can have any of the following key/value pairs:

  • nullable: for specifying whether a field is nullable (in SDL, each field is non-nullable by default); boolean
  • description: for setting a field description; string
  • deprecationReason: for marking a field as deprecated; string

For example:

  1. @Field({ description: `Book title`, deprecationReason: 'Not useful in v2 schema' })
  2. title: string;

Hint You can also add a description to, or deprecate, the whole object type: @ObjectType({ description: 'Author model' }).

When the field is an array, we must manually indicate the array type in the Field() decorator’s type function, as shown below:

  1. @Field(type => [Post])
  2. posts: Post[];

Hint Using array bracket notation ([ ]), we can indicate the depth of the array. For example, using [[Int]] would represent an integer matrix.

To declare that an array’s items (not the array itself) are nullable, set the nullable property to 'items' as shown below:

  1. @Field(type => [Post], { nullable: 'items' })
  2. posts: Post[];

Hint If both the array and its items are nullable, set nullable to 'itemsAndList' instead.

Now that the Author object type is created, let’s define the Post object type.

posts/models/post.model.ts

  1. import { Field, Int, ObjectType } from '@nestjs/graphql';
  2. @ObjectType()
  3. export class Post {
  4. @Field(type => Int)
  5. id: number;
  6. @Field()
  7. title: string;
  8. @Field(type => Int, { nullable: true })
  9. votes?: number;
  10. }

The Post object type will result in generating the following part of the GraphQL schema in SDL:

schema.gql.ts

  1. type Post {
  2. id: Int!
  3. title: String!
  4. votes: Int
  5. }

Code first resolver

At this point, we’ve defined the objects (type definitions) that can exist in our data graph, but clients don’t yet have a way to interact with those objects. To address that, we need to create a resolver class. In the code first method, a resolver class both defines resolver functions and generates the Query type. This will be clear as we work through the example below:

authors/authors.resolver.ts

  1. @Resolver(of => Author)
  2. export class AuthorsResolver {
  3. constructor(
  4. private authorsService: AuthorsService,
  5. private postsService: PostsService,
  6. ) {}
  7. @Query(returns => Author)
  8. async author(@Args('id', { type: () => Int }) id: number) {
  9. return this.authorsService.findOneById(id);
  10. }
  11. @ResolveField()
  12. async posts(@Parent() author: Author) {
  13. const { id } = author;
  14. return this.postsService.findAll({ authorId: id });
  15. }
  16. }

Hint All decorators (e.g., @Resolver, @ResolveField, @Args, etc.) are exported from the @nestjs/graphql package.

You can define multiple resolver classes. Nest will combine these at run time. See the module section below for more on code organization.

Note The logic inside the AuthorsService and PostsService classes can be as simple or sophisticated as needed. The main point of this example is to show how to construct resolvers and how they can interact with other providers.

In the example above, we created the AuthorsResolver which defines one query resolver function and one field resolver function. To create a resolver, we create a class with resolver functions as methods, and annotate the class with the @Resolver() decorator.

In this example, we defined a query handler to get the author object based on the id sent in the request. To specify that the method is a query handler, use the @Query() decorator.

The argument passed to the @Resolver() decorator is optional, but comes into play when our graph becomes non-trivial. It’s used to supply a parent object used by field resolver functions as they traverse down through an object graph.

In our example, since the class includes a field resolver function (for the posts property of the Author object type), we must supply the @Resolver() decorator with a value to indicate which class is the parent type (i.e., the corresponding ObjectType class name) for all field resolvers defined within this class. As should be clear from the example, when writing a field resolver function, it’s necessary to access the parent object (the object the field being resolved is a member of). In this example, we populate an author’s posts array with a field resolver that calls a service which takes the author’s id as an argument. Hence the need to identify the parent object in the @Resolver() decorator. Note the corresponding use of the @Parent() method parameter decorator to then extract a reference to that parent object in the field resolver.

We can define multiple @Query() resolver functions (both within this class, and in any other resolver class), and they will be aggregated into a single Query type definition in the generated SDL along with the appropriate entries in the resolver map. This allows you to define queries close to the models and services that they use, and to keep them well organized in modules.

Query type names

In the above examples, the @Query() decorator generates a GraphQL schema query type name based on the method name. For example, consider the following construction from the example above:

  1. @Query(returns => Author)
  2. async author(@Args('id', { type: () => Int }) id: number) {
  3. return this.authorsService.findOneById(id);
  4. }

This generates the following entry for the author query in our schema (the query type uses the same name as the method name):

  1. type Query {
  2. author(id: Int!): Author
  3. }

Hint Learn more about GraphQL queries here.

Conventionally, we prefer to decouple these names; for example, we prefer to use a name like getAuthor() for our query handler method, but still use author for our query type name. The same applies to our field resolvers. We can easily do this by passing the mapping names as arguments of the @Query() and @ResolveField() decorators, as shown below:

authors/authors.resolver.ts

  1. @Resolver(of => Author)
  2. export class AuthorsResolver {
  3. constructor(
  4. private authorsService: AuthorsService,
  5. private postsService: PostsService,
  6. ) {}
  7. @Query(returns => Author, { name: 'author' })
  8. async getAuthor(@Args('id', { type: () => Int }) id: number) {
  9. return this.authorsService.findOneById(id);
  10. }
  11. @ResolveField('posts', returns => [Post])
  12. async getPosts(@Parent() author: Author) {
  13. const { id } = author;
  14. return this.postsService.findAll({ authorId: id });
  15. }
  16. }

The getAuthor handler method above will result in generating the following part of the GraphQL schema in SDL:

  1. type Query {
  2. author(id: Int!): Author
  3. }

Query decorator options

The @Query() decorator’s options object (where we pass {name: 'author'} above) accepts a number of key/value pairs:

  • name: name of the query; a string
  • description: a description that will be used to generate GraphQL schema documentation (e.g., in GraphQL playground); a string
  • deprecationReason: sets query metadata to show the query as deprecated (e.g., in GraphQL playground); a string
  • nullable: whether the query can return a null data response; boolean or 'items' or 'itemsAndList' (see above for details of 'items' and 'itemsAndList')

Args decorator options

Use the @Args() decorator to extract arguments from a request for use in the method handler. This works in a very similar fashion to REST route parameter argument extraction.

Usually your @Args() decorator will be simple, and not require an object argument as seen with the getAuthor() method above. For example, if the type of an identifier is string, the following construction is sufficient, and simply plucks the named field from the inbound GraphQL request for use as a method argument.

  1. @Args('id') id: string

In the getAuthor() case, the number type is used, which presents a challenge. The number TypeScript type doesn’t give us enough information about the expected GraphQL representation (e.g., Int vs. Float). Thus we have to explicitly pass the type reference. We do that by passing a second argument to the Args() decorator, containing argument options, as shown below:

  1. @Query(returns => Author, { name: 'author' })
  2. async getAuthor(@Args('id', { type: () => Int }) id: number) {
  3. return this.authorsService.findOneById(id);
  4. }

The options object allows us to specify the following optional key value pairs:

  • type: a function returning the GraphQL type
  • defaultValue: a default value; any
  • description: description metadata; string
  • deprecationReason: to deprecate a field and provide meta data describing why; string
  • nullable: whether the field is nullable

Query handler methods can take multiple arguments. Let’s imagine that we want to fetch an author based on its firstName and lastName. In this case, we can call @Args twice:

  1. getAuthor(
  2. @Args( 'firstName', { nullable: true }) firstName?: string,
  3. @Args( 'lastName', { defaultValue: '' }) lastName?: string,
  4. ) {}

Dedicated arguments class

With inline @Args() calls, code like the example above becomes bloated. Instead, you can create a dedicated GetAuthorArgs arguments class and access it in the handler method as follows:

  1. @Args() args: GetAuthorArgs

Create the GetAuthorArgs class using @ArgsType() as shown below:

authors/dto/get-author.args.ts

  1. import { MinLength } from 'class-validator';
  2. import { Field, ArgsType } from '@nestjs/graphql';
  3. @ArgsType()
  4. class GetAuthorArgs {
  5. @Field({ nullable: true })
  6. firstName?: string;
  7. @Field({ defaultValue: '' })
  8. @MinLength(3)
  9. lastName: string;
  10. }

Hint Again, due to TypeScript’s metadata reflection system limitations, it’s required to either use the @Field decorator to manually indicate type and optionality, or use a CLI plugin.

This will result in generating the following part of the GraphQL schema in SDL:

  1. type Query {
  2. author(firstName: String, lastName: String = ''): Author
  3. }

Hint Note that arguments classes like GetAuthorArgs play very well with the ValidationPipe (read more).

Class inheritance

You can use standard TypeScript class inheritance to create base classes with generic utility type features (fields and field properties, validations, etc.) that can be extended. For example, you may have a set of pagination related arguments that always include the standard offset and limit fields, but also other index fields that are type-specific. You can set up a class hierarchy as shown below.

Base @ArgsType() class:

  1. @ArgsType()
  2. class PaginationArgs {
  3. @Field((type) => Int)
  4. offset: number = 0;
  5. @Field((type) => Int)
  6. limit: number = 10;
  7. }

Type specific sub-class of the base @ArgsType() class:

  1. @ArgsType()
  2. class GetAuthorArgs extends PaginationArgs {
  3. @Field({ nullable: true })
  4. firstName?: string;
  5. @Field({ defaultValue: '' })
  6. @MinLength(3)
  7. lastName: string;
  8. }

The same approach can be taken with @ObjectType() objects. Define generic properties on the base class:

  1. @ObjectType()
  2. class Character {
  3. @Field((type) => Int)
  4. id: number;
  5. @Field()
  6. name: string;
  7. }

Add type-specific properties on sub-classes:

  1. @ObjectType()
  2. class Warrior extends Character {
  3. @Field()
  4. level: number;
  5. }

You can use inheritance with a resolver as well. You can ensure type safety by combining inheritance and TypeScript generics. For example, to create a base class with a generic findAll query, use a construction like this:

  1. function BaseResolver<T extends Type<unknown>>(classRef: T): any {
  2. @Resolver({ isAbstract: true })
  3. abstract class BaseResolverHost {
  4. @Query((type) => [classRef], { name: `findAll${classRef.name}` })
  5. async findAll(): Promise<T[]> {
  6. return [];
  7. }
  8. }
  9. return BaseResolverHost;
  10. }

Note the following:

  • an explicit return type (any above) is required: otherwise TypeScript complains about the usage of a private class definition. Recommended: define an interface instead of using any.
  • Type is imported from the @nestjs/common package
  • The isAbstract: true property indicates that SDL (Schema Definition Language statements) shouldn’t be generated for this class. Note, you can set this property for other types as well to suppress SDL generation.

Here’s how you could generate a concrete sub-class of the BaseResolver:

  1. @Resolver((of) => Recipe)
  2. export class RecipesResolver extends BaseResolver(Recipe) {
  3. constructor(private recipesService: RecipesService) {
  4. super();
  5. }
  6. }

This construct would generated the following SDL:

  1. type Query {
  2. findAllRecipe: [Recipe!]!
  3. }

Generics

We saw one use of generics above. This powerful TypeScript feature can be used to create useful abstractions. For example, here’s a sample cursor-based pagination implementation based on this documentation:

  1. import { Field, ObjectType, Int } from '@nestjs/graphql';
  2. import { Type } from '@nestjs/common';
  3. export function Paginated<T>(classRef: Type<T>): any {
  4. @ObjectType(`${classRef.name}Edge`)
  5. abstract class EdgeType {
  6. @Field((type) => String)
  7. cursor: string;
  8. @Field((type) => classRef)
  9. node: T;
  10. }
  11. @ObjectType({ isAbstract: true })
  12. abstract class PaginatedType {
  13. @Field((type) => [EdgeType], { nullable: true })
  14. edges: EdgeType[];
  15. @Field((type) => [classRef], { nullable: true })
  16. nodes: T[];
  17. @Field((type) => Int)
  18. totalCount: number;
  19. @Field()
  20. hasNextPage: boolean;
  21. }
  22. return PaginatedType;
  23. }

With the above base class defined, we can now easily create specialized types that inherit this behavior. For example:

  1. @ObjectType()
  2. class PaginatedAuthor extends Paginated(Author) {}

Schema first

As mentioned in the previous chapter, in the schema first approach we start by manually defining schema types in SDL (read more). Consider the following SDL type definitions.

Hint For convenience in this chapter, we’ve aggregated all of the SDL in one location (e.g., one .graphql file, as shown below). In practice, you may find it appropriate to organize your code in a modular fashion. For example, it can be helpful to create individual SDL files with type definitions representing each domain entity, along with related services, resolver code, and the Nest module definition class, in a dedicated directory for that entity. Nest will aggregate all the individual schema type definitions at run time.

  1. type Author {
  2. id: Int!
  3. firstName: String
  4. lastName: String
  5. posts: [Post]
  6. }
  7. type Post {
  8. id: Int!
  9. title: String!
  10. votes: Int
  11. }
  12. type Query {
  13. author(id: Int!): Author
  14. }

Schema first resolver

The schema above exposes a single query - author(id: Int!): Author.

Hint Learn more about GraphQL queries here.

Let’s now create an AuthorsResolver class that resolves author queries:

authors/authors.resolver.ts

  1. @Resolver('Author')
  2. export class AuthorsResolver {
  3. constructor(
  4. private authorsService: AuthorsService,
  5. private postsService: PostsService,
  6. ) {}
  7. @Query()
  8. async author(@Args('id') id: number) {
  9. return this.authorsService.findOneById(id);
  10. }
  11. @ResolveField()
  12. async posts(@Parent() author) {
  13. const { id } = author;
  14. return this.postsService.findAll({ authorId: id });
  15. }
  16. }

Hint All decorators (e.g., @Resolver, @ResolveField, @Args, etc.) are exported from the @nestjs/graphql package.

Note The logic inside the AuthorsService and PostsService classes can be as simple or sophisticated as needed. The main point of this example is to show how to construct resolvers and how they can interact with other providers.

The @Resolver() decorator is required. It takes an optional string argument with the name of a class. This class name is required whenever the class includes @ResolveField() decorators to inform Nest that the decorated method is associated with a parent type (the Author type in our current example). Alternatively, instead of setting @Resolver() at the top of the class, this can be done for each method:

  1. @Resolver('Author')
  2. @ResolveField()
  3. async posts(@Parent() author) {
  4. const { id } = author;
  5. return this.postsService.findAll({ authorId: id });
  6. }

In this case (@Resolver() decorator at the method level), if you have multiple @ResolveField() decorators inside a class, you must add @Resolver() to all of them. This is not considered the best practice (as it creates extra overhead).

Hint Any class name argument passed to @Resolver()does not affect queries (@Query() decorator) or mutations (@Mutation() decorator).

Warning Using the @Resolver decorator at the method level is not supported with the code first approach.

In the above examples, the @Query() and @ResolveField() decorators are associated with GraphQL schema types based on the method name. For example, consider the following construction from the example above:

  1. @Query()
  2. async author(@Args('id') id: number) {
  3. return this.authorsService.findOneById(id);
  4. }

This generates the following entry for the author query in our schema (the query type uses the same name as the method name):

  1. type Query {
  2. author(id: Int!): Author
  3. }

Conventionally, we would prefer to decouple these, using names like getAuthor() or getPosts() for our resolver methods. We can easily do this by passing the mapping name as an argument to the decorator, as shown below:

authors/authors.resolver.ts.ts

  1. @Resolver('Author')
  2. export class AuthorsResolver {
  3. constructor(
  4. private authorsService: AuthorsService,
  5. private postsService: PostsService,
  6. ) {}
  7. @Query('author')
  8. async getAuthor(@Args('id') id: number) {
  9. return this.authorsService.findOneById(id);
  10. }
  11. @ResolveField('posts')
  12. async getPosts(@Parent() author) {
  13. const { id } = author;
  14. return this.postsService.findAll({ authorId: id });
  15. }
  16. }

Generating types

Assuming that we use the schema first approach and have enabled the typings generation feature (with outputAs: 'class' as shown in the previous chapter), once you run the application it will generate the following file (in the location you specified in the GraphQLModule.forRoot() method. For example, in src/graphql.ts)

graphql.ts.ts

  1. export class Author {
  2. id: number;
  3. firstName?: string;
  4. lastName?: string;
  5. posts?: Post[];
  6. }
  7. export class Post {
  8. id: number;
  9. title: string;
  10. votes?: number;
  11. }
  12. export abstract class IQuery {
  13. abstract author(id: number): Author | Promise<Author>;
  14. }

By generating classes (instead of the default technique of generating interfaces), you can use declarative validation decorators in combination with the schema first approach, which is an extremely useful technique (read more). For example, you could add class-validator decorators to the generated CreatePostInput class as shown below to enforce minimum and maximum string lengths on the title field:

  1. import { MinLength, MaxLength } from 'class-validator';
  2. export class CreatePostInput {
  3. @MinLength(3)
  4. @MaxLength(50)
  5. title: string;
  6. }

Notice To enable auto-validation of your inputs (and parameters), use ValidationPipe. Read more about validation here and more specifically about pipes here.

However, if you add decorators directly to the automatically generated file, they will be overwritten each time the file is generated. Instead, create a separate file and simply extend the generated class.

  1. import { MinLength, MaxLength } from 'class-validator';
  2. import { Post } from '../../graphql.ts';
  3. export class CreatePostInput extends Post {
  4. @MinLength(3)
  5. @MaxLength(50)
  6. title: string;
  7. }

GraphQL argument decorators

We can access the standard GraphQL resolver arguments using dedicated decorators. Below is a comparison of the Nest decorators and the plain Apollo parameters they represent.

@Root() and @Parent()root/parent
@Context(param?: string)context / context[param]
@Info(param?: string)info / info[param]
@Args(param?: string)args / args[param]

These arguments have the following meanings:

  • root: an object that contains the result returned from the resolver on the parent field, or, in the case of a top-level Query field, the rootValue passed from the server configuration.
  • context: an object shared by all resolvers in a particular query; typically used to contain per-request state.
  • info: an object that contains information about the execution state of the query.
  • args: an object with the arguments passed into the field in the query.

Hoodies, T-shirts, and accessories!

Support our future development by shopping in the official store!

See more

Module

Once we’re done with the above steps, we have declaratively specified all the information needed by the GraphQLModule to generate a resolver map. The GraphQLModule uses reflection to introspect the meta data provided via the decorators, and transforms classes into the correct resolver map automatically.

The only other thing you need to take care of is to provide (i.e., list as a provider in some module) the resolver class(es) (AuthorsResolver), and importing the module (AuthorsModule) somewhere, so Nest will be able to utilize it.

For example, we can do this in an AuthorsModule, which can also provide other services needed in this context. Be sure to import AuthorsModule somewhere (e.g., in the root module, or some other module imported by the root module).

authors/authors.module.ts

  1. @Module({
  2. imports: [PostsModule],
  3. providers: [AuthorsService, AuthorsResolver],
  4. })
  5. export class AuthorsModule {}

Hint It is helpful to organize your code by your so-called domain model (similar to the way you would organize entry points in a REST API). In this approach, keep your models (ObjectType classes), resolvers and services together within a Nest module representing the domain model. Keep all of these components in a single folder per module. When you do this, and use the Nest CLI to generate each element, Nest will wire all of these parts together (locating files in appropriate folders, generating entries in provider and imports arrays, etc.) automatically for you.