LoginSignup
1
0

More than 3 years have passed since last update.

【NestJS】ヘルスチェック(v6版)

Last updated at Posted at 2020-02-12

やりたいこと

NestJS x TypeORM の環境で、DBまで一気通貫したヘルスチェック用URLを作りたい。
terminusというNodeJS用のパッケージで、NestJS用のものがあるので、それを使います。

NestJS 7 版

こちらを参照してください。

環境

インストール

yarn add @nestjs/terminus @godaddy/terminus --no-optional

// or

npm install --save @nestjs/terminus @godaddy/terminus --no-optional

参照: https://github.com/nestjs/terminus#installation

実装

  • ほとんど、↓のページに書いている通りです。

  • src/health/health.module.ts に置いていますが、場所は任意です。

src/health/health.module.ts
import { TYPE_ORM_CONFIG } from '../config/app.config'

import { Module } from '@nestjs/common'
import {
  TerminusModule,
  TerminusModuleOptions,
  TypeOrmHealthIndicator,
  HealthIndicatorResult,
} from '@nestjs/terminus'
import { TypeOrmModule } from '@nestjs/typeorm'

const getTerminusOptions = (
  db: TypeOrmHealthIndicator
): TerminusModuleOptions => ({
  endpoints: [
    {
      url: '/health',
      healthIndicators: [
        // Set the timeout for a response to 300ms
        async (): Promise<HealthIndicatorResult> =>
          db.pingCheck('database', { timeout: 300 }),
      ],
    },
  ],
})

@Module({
  imports: [
    TypeOrmModule.forRoot(TYPE_ORM_CONFIG),
    TerminusModule.forRootAsync({
      inject: [TypeOrmHealthIndicator],
      useFactory: (db) => getTerminusOptions(db),
    }),
  ],
})
export class HealthModule {}
  • src/app.module.tsimportsに追加します。
src/app.module.ts
import { HealthModule } from './health/health.module'  // この行と、、、

   imports: [
     TypeOrmModule.forRoot(TYPE_ORM_CONFIG),
     HealthModule,                                     // この行を追加 

前提

↑の前提として、TYPE_ORM_CONFIGconfig/app.config)に、DBの定義情報が設定されている必要があります。以下、例です。

src/config/app.config.ts
import { TypeOrmModuleOptions } from '@nestjs/typeorm'

export const TYPE_ORM_CONFIG: TypeOrmModuleOptions = {
  type: 'mysql',
  charset: 'utf8mb4_bin',
  host: process.env.DB_HOST || 'localhost',
  port: +(process.env.DB_PORT || 3306),
  username: process.env.DB_USERNAME || 'root',
  password: process.env.DB_PASSWORD,
  database: process.env.DB_DATABASE || 'your_database_name_comes_here',
  entities: [__dirname + '/../**/*.entity.{js,ts}'],
}

動作確認ログ

$ curl -X GET "http://localhost:3000/health"
{"status":"ok","info":{"database":{"status":"up"}},"details":{"database":{"status":"up"}}}% 
// DBに対して SELECT 1 が実行されていることが確認できます。

$ yarn start:dev
:
{"level":30,"time":1581485016754,"pid":62278,"hostname":"xl.local","msg":"Server listening at http://0.0.0.0:3000","v":1}
query: SELECT 1
1
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
1
0