開発覚書はてな版

個人的な開発関連の備忘録

【NestJS】NestJSでGraphQL を使ってみた - Code frist編

概要

今回はNestJSでGraphQL を使用したサンプルです。
Code fristとSchema firstの2つのアプローチがあります。今回はCode fristのアプローチで実装していきたいと思います。

GraphQL については以下のページを参照 graphql.org

NestJSのGraphQL の説明記事 docs.nestjs.com

実行環境

  • Node.js - 12.x

使用ライブラリ

  • @nestjs/common - 7.4.x
  • @nestjs/core - 7.4.x
  • @nestjs/graphql - 7.6.x
  • @nestjs/platform-express - 7.4.x
  • apollo-server-express"- 2.16.x
  • graphql - 15.3.x
  • graphql-tools - 6.0.x

サンプルソース

author.model.ts

  • GraphQLで使用する型情報をデコレータで指定します。
import { Field, Int, ObjectType } from '@nestjs/graphql';

@ObjectType()
export class Author {
  @Field(() => Int)
  id: number;

  @Field({ nullable: true })
  firstName?: string;

  @Field({ nullable: true })
  lastName?: string;
}

authors.resolver.ts

  • @Resolver をクラスに定義します。GraphQL関連の操作を行うクラスとして定義されます。
  • @Query をメソッドに定義します。GraphQLのクエリの動作をメソッド内に記述します。
import { Args, Int, Query, Resolver } from '@nestjs/graphql';

import { Author } from './author.model';

@Resolver(() => Author)
export class AuthorResolver {
  readonly authorMaps = new Map<number, Author>([
    [1, { id: 1, firstName: 'hige', lastName: 'hoge' }],
    [2, { id: 2, firstName: 'sample', lastName: 'user' }],
    [3, { id: 3, firstName: 'sample', lastName: 'hoge' }],
  ]);

  @Query(() => Author)
  async author(@Args('id', { type: () => Int }) id: number) {
    return this.authorMaps.get(id);
  }
}

app.module.ts

  • AuthorResolverをprovidersに設定します。
  • GraphQLModule.forRoot の設定は以下の通りです。
    • autoSchemaFile: true :GraphQLのスキーマをメモリー上に保持します。
    • playground: true:GraphQL playground機能を有効化します。未指定の場合もtrueになります。
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';

import { AuthorResolver } from './authors.resolver';

@Module({
  providers: [AuthorResolver],
  imports: [GraphQLModule.forRoot({ autoSchemaFile: true, playground: true })],
})
export class AppModule {}

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

実行結果

  • /http://localhost:3000/graphql にブラウザからアクセスすることで、GraphQL playgroundが表示されます。
  • GraphQL playground上でクエリを入力することで、動作確認ができます。

f:id:kakkoya:20200806111920p:plain

以下はクエリのサンプルです。

{
  author(id: 1) {
    id
    firstName
  }
}

サンプルソース一式

github.com

おわりに

  • GraphQL playgroundの起動までが簡単に実装出来ました。
  • NestJSには様々な拡張が入っているため色々調べるのが楽しいです。