0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nest.jsでコードファーストのGraphQLをやる

Last updated at Posted at 2025-07-12

説明

この記事では、NestJSプロジェクトにGraphQL(コードファースト方式)を導入し、必要なライブラリのインストールから、GraphQL経由でhealthチェックができるようになるまでの手順を、サンプルコード付きでわかりやすく解説します。


必要なライブラリのインストール

以下のコマンドでGraphQL関連のライブラリをインストールします。

# GraphQL本体とNestJS用のGraphQLモジュール、Apolloサーバーをインストール
yarn add @nestjs/graphql @nestjs/apollo graphql apollo-server-express

# 型定義(開発用)
yarn add -D @types/graphql

GraphQLセットアップ手順

  1. GraphQLModuleAppModule に追加します。
  2. Healthチェック用のResolverを作成します。

1. GraphQLModuleの設定

app.module.ts に以下を追加します。

// app.module.ts
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { HealthResolver } from './health.resolver';

@Module({
  imports: [
    GraphQLModule.forRoot({
      autoSchemaFile: 'schema.gql', // スキーマを自動生成
      playground: true, // GraphQL Playgroundを有効化
    }),
  ],
  providers: [HealthResolver],
})
export class AppModule {}

2. HealthResolverの作成

health.resolver.ts を作成し、healthチェック用のクエリを実装します。

// health.resolver.ts
import { Query, Resolver } from '@nestjs/graphql';

@Resolver()
export class HealthResolver {
  // healthクエリで"ok"を返す
  @Query(() => String)
  health(): string {
    return 'ok';
  }
}

3. サーバー起動と動作確認

yarn start:dev

http://localhost:3000/graphql にアクセスし、以下のクエリでhealthチェックできます。

query {
  health
}

レスポンス例:

{
  "data": {
    "health": "ok"
  }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?