Add a GraphQL endpoint to a NestJS API

Bram Borggreve
InstructorBram Borggreve
Share this video with your friends

Social Share Links

Send Tweet

In this lesson, we will add GraphQL functionality to our NestJS API. After installing a bunch of dependencies, we can import the GraphQLModule inside our CoreModule. We call the forRoot method and pass in an object that sets autoSchemaFile to true.

This enables the code-first option in NestJS. This means that we can generate our GraphQL schema by adding decorators to classes!

When restarting the API, we see that we get an error message telling us that the "query root type is required". This is because each GraphQL server should have at least one query.

We create and provide the CoreResolver and define a method uptime that returns process.uptime(). To expose this method over GraphQL we decorate it with the @Query decorator, and make sure that we import it from @nestjs/graphql.

Bram Borggreve: [0:00] We install the dependencies @nestjs/graphql graphql graphql-tools and apollo-server-express. Additionally, we add class-validator and class-transformer so we can do validation.

[0:14] We open the core.module from libs/core/src/lib. Inside the imports array, we import GraphQLModule and call the forRoot() method. We pass in an object and set autoSchemaFile to true. This enables to call first option of GraphQL for nest.

[0:29] When we look at our server, we see that we have an error, "Query root type must be provided." This is because each GraphQL server should have at least one query. Let's go and add one.

[0:41] Next to core.module.ts we create a file called core.resolver.ts. We export class CoreResolver and decorate it with the @Resolver decorator that gets imported from @nestjs/graphql. Inside our class, we define a method called uptime() and make it return process.uptime().

[0:59] To expose this method over GraphQL, we need to decorate it with the @Query decorator. Make sure to import Query from @nestjs/graphql and not from @nestjs/common. Inside the @Query decorator we define a return type, in this case a Float, that also gets imported from @nestjs/graphql.

[1:17] In the core.module we add CoreResolver to the providers array and make sure that we import it. When we now restart the API, we see that the GraphQLModule is loaded.

[1:27] Let's quickly open our main.ts from apps/api/src and duplicate the listening online and have it return the URL to the GraphQL Playground. We can now open the GraphQL Playground and execute our query.