Add a GraphQL endpoint to a NestJS API

InstructorBram Borggreve

Share this video with your friends

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.