In this chapter we will add GraphQL module and set up an Apollo Studio playground to test a basic “Foo” resolver.
Official doc is also recommended:
https://docs.nestjs.com/graphql/quick-start
https://docs.nestjs.com/graphql/resolvers
Install NPM packages
npm i @nestjs/graphql @nestjs/apollo graphql apollo-server-express apollo-server-core
Add GraphQL Module to App Module (we are using code first approach)
// app.module.ts
import { join } from 'path';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloServerPluginLandingPageLocalDefault } from 'apollo-server-core';
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
debug: true,
autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
sortSchema: true,
playground: false,
plugins: [ApolloServerPluginLandingPageLocalDefault()],
}),
Create a basic FooResolver to get started:
// app.resolver.ts
/* eslint-disable class-methods-use-this */
import { Query, Resolver } from '@nestjs/graphql';
@Resolver()
export default class FooResolver {
@Query(() => String)
sayHello() {
return 'Hello World!';
}
}
This simply provides a GQL query that returns Hello World!
Add the resolver to App Module:
// app.module.ts
import FooResolver from './app.resolver';
//..
providers: [FooResolver],
Then we can test the GQL query in local Apollo Studio: http://localhost:3000/graphql