Unions

Union types are very similar to interfaces, but they don’t get to specify any common fields between the types (read more here). Unions are useful for returning disjoint data types from a single field.

Code first

To define a GraphQL union type, we must define classes that this union will be composed of. Following the example from the Apollo documentation, we’ll create two classes. First, Book:

  1. import { Field, ObjectType } from '@nestjs/graphql';
  2. @ObjectType()
  3. export class Book {
  4. @Field()
  5. title: string;
  6. }

And then Author:

  1. import { Field, ObjectType } from '@nestjs/graphql';
  2. @ObjectType()
  3. export class Author {
  4. @Field()
  5. name: string;
  6. }

With this in place, register the ResultUnion union using the createUnionType function exported from the @nestjs/graphql package:

  1. export const ResultUnion = createUnionType({
  2. name: 'ResultUnion',
  3. types: () => [Author, Book],
  4. });

Now, we can reference the ResultUnion in our query:

  1. @Query(returns => [ResultUnion])
  2. search(): Array<typeof ResultUnion> {
  3. return [new Author(), new Book()];
  4. }

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

  1. type Author {
  2. name: String!
  3. }
  4. type Book {
  5. title: String!
  6. }
  7. union ResultUnion = Author | Book
  8. type Query {
  9. search: [ResultUnion!]!
  10. }

The default resolveType() function generated by the library will extract the type based on the value returned from the resolver method. That means returning class instances instead of literal JavaScript object is obligatory.

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

  1. export const ResultUnion = createUnionType({
  2. name: 'ResultUnion',
  3. types: () => [Author, Book],
  4. resolveType(value) {
  5. if (value.name) {
  6. return Author;
  7. }
  8. if (value.title) {
  9. return Book;
  10. }
  11. return null;
  12. },
  13. });

Schema first

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

  1. type Author {
  2. name: String!
  3. }
  4. type Book {
  5. title: String!
  6. }
  7. union ResultUnion = Author | Book

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

  1. export class Author {
  2. name: string;
  3. }
  4. export class Book {
  5. title: string;
  6. }
  7. export type ResultUnion = Author | Book;

Unions require an extra __resolveType field in the resolver map to determine which type the union should resolve to. Also, note that the ResultUnionResolver class has to be registered as a provider in any module. Let’s create a ResultUnionResolver class and define the __resolveType method.

  1. @Resolver('ResultUnion')
  2. export class ResultUnionResolver {
  3. @ResolveField()
  4. __resolveType(value) {
  5. if (value.name) {
  6. return 'Author';
  7. }
  8. if (value.title) {
  9. return 'Book';
  10. }
  11. return null;
  12. }
  13. }

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

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. }

To provide a description for the enum, pass the description property into the registerEnumType() function.

  1. registerEnumType(AllowedColor, {
  2. name: 'AllowedColor',
  3. description: 'The supported colors.',
  4. });

To provide a description for the enum values, or to mark a value as deprecated, pass the valuesMap property, as follows:

  1. registerEnumType(AllowedColor, {
  2. name: 'AllowedColor',
  3. description: 'The supported colors.',
  4. valuesMap: {
  5. RED: {
  6. description: 'The default color.',
  7. },
  8. BLUE: {
  9. deprecationReason: 'Too blue.',
  10. },
  11. },
  12. });

This will generate the following GraphQL schema in SDL:

  1. """
  2. The supported colors.
  3. """
  4. enum AllowedColor {
  5. """
  6. The default color.
  7. """
  8. RED
  9. GREEN
  10. BLUE @deprecated(reason: "Too blue.")
  11. }

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. };

info 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. });