Add GraphQL to a NestJS API in a Nx Workspace
Tags: api, nest, graphql, node
Published: 2020-08-20 03:51:07

---
title: "Add GraphQL to a NestJS API in a Nx Workspace"
series: "Building API's with NestJS and Nrwl Nx"
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/3lapwr5f7xlnzlqfs7vv.png
published: true
tags: api, nest, graphql, node
---

## Introduction

In this tutorial, we add GraphQL functionality to the API using the [@nestjs/graphql](https://docs.nestjs.com/graphql/quick-start) package.

GraphQL is a specification for a strongly-typed query language for API's, and is well-supported by NestJS. If you're not familiar with GraphQL you can read [this introduction](https://graphql.org/learn/).

## 1. Install and configure the @nestjs/graphql package.

In order to use GraphQL, we need to install the dependencies and configure the `GraphQLModule`.

### 1.1 Install the dependencies

```bash
yarn add @nestjs/graphql graphql-tools graphql apollo-server-express
```

We install the `apollo-server-express` dependency because NestJS uses [express](https://expressjs.com/) by default. Next to Express there is also support for [Fastify](https://www.fastify.io/).

### 1.2 Import the Module

Open `libs/core/src/lib/core.module.ts` and add the following lint on the top:

```typescript
import { GraphQLModule } from "@nestjs/graphql";
```

Next, add the `GraphQLModule` to the `imports` array in the `Module` decorator:

```typescript
@Module({
  imports: [
    // The ConfigModule lives here
    GraphQLModule.forRoot({
      autoSchemaFile: true
    })
  ]
  // The controllers, providers, exports arrays live here.
})
export class CoreModule {}
```

To initialize the `GraphQLModule`, we invoke the `forRoot()` method and pass it an object with the property `autoSchemaFile` set to `true`.

Setting `autoSchemaFile` set to `true` enables the [_code-first_](https://docs.nestjs.com/graphql/quick-start#code-first) approach, which means that we can define our GraphQL schema by writing TypeScript classes with decorators, and NestJS will generate the actual GraphQL schema file based on that.

### 2 Add a Resolver

When you restart the dev server, you will get an error:

    GraphQLError: Query root type must be provided.

This is because a GraphQL server must have at least one _Query_ defined, and currently we have none. Time to add one and make the server run again!

### 2.1 Implement the CoreResolver

Create the file `libs/core/src/lib/core.resolver.ts` and add the following snippet:

```typescript
import { Float, Query, Resolver } from "@nestjs/graphql";

@Resolver()
export class CoreResolver {
  @Query(() => Float)
  uptime() {
    return process.uptime();
  }
}
```

This class, that is decorated with the _@Resolver()_ decorator, that has two functions:

- It defines which GraphQL _queries_ exists, and what _type_ these queries returns.
- It defines which code to execute when this query is invoked.

The queries can be defined by adding the `@Query` decorator to a method. The decorator will, by default, use the name of the method that is decorated, so our first query is called `uptime`. Inside the decorator is an anonymous function that returns the _type_, in our case this is a _Float_.

Inside the method body we simply return `process.uptime()`, which returns the _uptime_ of the server.

> 💡 Make sure to import the `Query` decorator from the `@nestjs/graphql` package. The `@nestjs/common` package also exports a `Query` decorator, but that one is uses for REST API's.

### 2.2 Provide the CoreResolver in the CoreModule

Open `libs/core/src/lib/core.module.ts` and add the following lint on the top:

```typescript
import { CoreResolver } from "./core.resolver";
```

Next, add the `CoreResolver` to the `providers` array in the `Module` decorator:

```typescript
@Module({
  // The imports and controllers live here
  providers: [CoreResolver]
  // The exports live here
})
export class CoreModule {}
```

With this in place, the server should start again!

Visit [http://localhost:3000/graphql](http://localhost:3000/graphql) to load the GraphQL Playground.

To test it, add the following query in the left-hand panel and click the Play button. The output should be similar to what you see in the screenshot.

```graphql
query {
  uptime
}
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/oitovkp3u47wp8afw1ts.png)

## Summary

In this tutorial, we added support for GraphQL to our API.

After installing the dependencies, we configured the `GraphQLModule` in the `CoreModule`.

Because a GraphQL server always needs at least one query, we implemented a _resolver_ called `CoreResolver` and exposed a simple query called `uptime`.

To verify that this all worked, we launched the playground and tested the query.

In the next tutorial, the last one of this series, we will expose our server to Heroku! Stay tuned!

## Thanks!

Thanks for reading my article, I hope it was useful. Feel free to reach out and follow me on [Twitter](https://twitter.com/beeman_nl/) or leave a comment on DEV! 🐝