๐Ÿ“ฆ nestjs / terminus

๐Ÿ“„ health-check.service.ts ยท 65 lines
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
65import {
  Injectable,
  ServiceUnavailableException,
  Inject,
  ConsoleLogger,
  LoggerService,
} from '@nestjs/common';
import { ErrorLogger } from './error-logger/error-logger.interface';
import { ERROR_LOGGER } from './error-logger/error-logger.provider';
import { HealthCheckExecutor } from './health-check-executor.service';
import { type HealthCheckResult } from './health-check-result.interface';
import { type HealthIndicatorFunction } from '../health-indicator';
import { TERMINUS_LOGGER } from './logger/logger.provider';

/**
 * Handles Health Checks which can be used in
 * Controllers.
 */
@Injectable()
export class HealthCheckService {
  constructor(
    private readonly healthCheckExecutor: HealthCheckExecutor,
    @Inject(ERROR_LOGGER)
    private readonly errorLogger: ErrorLogger,
    @Inject(TERMINUS_LOGGER)
    private readonly logger: LoggerService,
  ) {
    if (this.logger instanceof ConsoleLogger) {
      this.logger.setContext(HealthCheckService.name);
    }
  }

  /**
   * Checks the given health indicators
   *
   * ```typescript
   *
   * healthCheckService.check([
   *   () => this.http.pingCheck('google', 'https://google.com'),
   * ]);
   *
   *
   * ```
   * @param healthIndicators The health indicators which should be checked
   */
  async check(
    healthIndicators: HealthIndicatorFunction[],
  ): Promise<HealthCheckResult> {
    const result = await this.healthCheckExecutor.execute(healthIndicators);
    if (result.status === 'ok') {
      return result;
    }

    if (result.status === 'error') {
      const msg = this.errorLogger.getErrorMessage(
        'Health Check has failed!',
        result.details,
      );
      this.logger.error(msg);
    }

    throw new ServiceUnavailableException(result);
  }
}