Interfaces

Like many type systems, GraphQL supports interfaces. An Interface is an abstract type that includes a certain set of fields that a type must include to implement the interface (read more here).

Code first

When using the code first approach, you define a GraphQL interface by creating an abstract class annotated with the @InterfaceType() decorator exported from the @nestjs/graphql.

  1. import { Field, ID, InterfaceType } from '@nestjs/graphql';
  2. @InterfaceType()
  3. export abstract class Character {
  4. @Field(type => ID)
  5. id: string;
  6. @Field()
  7. name: string;
  8. }

warning Warning TypeScript interfaces cannot be used to define GraphQL interfaces.

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

  1. interface Character {
  2. id: ID!
  3. name: String!
  4. }

Now, to implement the Character interface, use the implements key:

  1. @ObjectType({
  2. implements: () => [Character],
  3. })
  4. export class Human implements Character {
  5. id: string;
  6. name: string;
  7. }

info Hint The @ObjectType() decorator is exported from the @nestjs/graphql package.

The default resolveType() function generated by the library extracts the type based on the value returned from the resolver method. This means that you must return class instances (you cannot return literal JavaScript objects).

To provide a customized resolveType() function, pass the resolveType property to the options object passed into the @InterfaceType() decorator, as follows:

  1. @InterfaceType({
  2. resolveType(book) {
  3. if (book.colors) {
  4. return ColoringBook;
  5. }
  6. return TextBook;
  7. },
  8. })
  9. export abstract class Book {
  10. @Field(type => ID)
  11. id: string;
  12. @Field()
  13. title: string;
  14. }

Schema first

To define an interface in the schema first approach, simply create a GraphQL interface with SDL.

  1. interface Character {
  2. id: ID!
  3. name: String!
  4. }

Then, you can use the typings generation feature (as shown in the quick start chapter) to generate corresponding TypeScript definitions:

  1. export interface Character {
  2. id: string;
  3. name: string;
  4. }

Interfaces require an extra __resolveType field in the resolver map to determine which type the interface should resolve to. Let’s create a CharactersResolver class and define the __resolveType method:

  1. @Resolver('Character')
  2. export class CharactersResolver {
  3. @ResolveField()
  4. __resolveType(value) {
  5. if ('age' in value) {
  6. return Person;
  7. }
  8. return null;
  9. }
  10. }

info Hint All decorators are exported from the @nestjs/graphql package.