Enums

Enumeration types are a special kind of scalar that is restricted to a particular set of allowed values (read more here). This allows you to:

  • validate that any arguments of this type are one of the allowed values
  • communicate through the type system that a field will always be one of a finite set of values

Code first

When using the code first approach, you define a GraphQL enum type by simply creating a TypeScript enum.

  1. export enum AllowedColor {
  2. RED,
  3. GREEN,
  4. BLUE,
  5. }

With this in place, register the AllowedColor enum using the registerEnumType function exported from the @nestjs/graphql package:

  1. registerEnumType(AllowedColor, {
  2. name: 'AllowedColor',
  3. });

Now you can reference the AllowedColor in our types:

  1. @Field(type => AllowedColor)
  2. favoriteColor: AllowedColor;

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

  1. enum AllowedColor {
  2. RED
  3. GREEN
  4. BLUE
  5. }

Schema first

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

  1. enum AllowedColor {
  2. RED
  3. GREEN
  4. BLUE
  5. }

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

  1. export enum AllowedColor {
  2. RED
  3. GREEN
  4. BLUE
  5. }

Sometimes a backend forces a different value for an enum internally than in the public API. In this example the API contains RED, however in resolvers we may use #f00 instead (read more here). To accomplish this, declare a resolver object for the AllowedColor enum:

  1. export const allowedColorResolver: Record<keyof typeof AllowedColor, any> = {
  2. RED: '#f00',
  3. }

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

Then use this resolver object together with the resolvers property of the GraphQLModule#forRoot() method, as follows:

  1. GraphQLModule.forRoot({
  2. resolvers: {
  3. AllowedColor: allowedColorResolver,
  4. },
  5. })