All files / src/modules/health health.controller.ts

58.06% Statements 18/31
68.75% Branches 11/16
12.5% Functions 1/8
55.17% Lines 16/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 7111x 11x         11x 11x 11x 11x     11x         11x 11x 11x   11x   11x 11x             11x                   11x                                                   11x      
import { Controller, Get } from '@nestjs/common';
import {
  HealthCheck,
  HealthCheckService,
  // HttpHealthIndicator,
} from '@nestjs/terminus';
import { ConfigService } from '@nestjs/config';
import { PrismaHealthIndicatorService } from '@app/modules/health/prisma.health';
import { Client as ESClient } from '@elastic/elasticsearch';
import Redis from 'ioredis';
 
@Controller()
export class HealthController {
  private esClient: ESClient;
  private redisClient: Redis;
 
  constructor(
    private readonly healthCheckService: HealthCheckService,
    private readonly prisma: PrismaHealthIndicatorService,
    private readonly config: ConfigService,
  ) {
    const node = this.config.get<string>('ELASTICSEARCH_NODE');
    // Fall back to localhost when env is missing to avoid crash in dev-container spins
    this.esClient = new ESClient({ node: node ?? 'http://localhost:9200' });
    this.redisClient = new Redis(this.config.get<string>('REDIS_URL') || 'redis://localhost:6379');
  }
 
  // ────── Liveness ───────────────────────────────────────────────
  // Simple "is the process up" probe – no external deps
  @Get('healthz')
  @HealthCheck()
  liveness() {
    return this.healthCheckService.check([
      async () => ({ self: { status: 'up' } }),
    ]);
  }
 
  // ────── Readiness ──────────────────────────────────────────────
  // Checks critical downstream deps – DB, Redis, ElasticSearch
  @Get('ready')
  @HealthCheck()
  readiness() {
    return this.healthCheckService.check([
      () => this.prisma.isHealthy('database'),
      async () => {
        try {
          await this.redisClient.ping();
          return { redis: { status: 'up' } };
        } catch (_unused) {
          throw new Error('Redis is down');
        }
      },
      async () => {
        try {
          await this.esClient.ping();
          return { elasticsearch: { status: 'up' } };
        } catch (_unused) {
          throw new Error('Elasticsearch is down');
        }
      },
    ]);
  }
 
  // ────── Standard Health Endpoint ───────────────────────────────
  // Alias for /ready - checks DB/Redis/ES connectivity
  @Get('health')
  @HealthCheck()
  health() {
    return this.readiness();
  }
}