Health checks

Checking if the system is healthy.

We may use Terminus to check the health of our components. It offers a set of health indicators, in order to confirm the overall health of the system. Let's then check the database health.

First, we should install the necessary dependency.

yarn add @nestjs/terminus

Now, create a resource for health with no CRUD, and inside the module import the TerminusModule.

nest g res health

In the controller, create a route for performing the health check.

@HealthCheck()
@Get()
check() {
  return this.healthService.check();
}

Note the @HealthCheck() decorator, which will make this route:

  • Be documented by Swagger

  • Not be cached

Then, in the service, inject the HealthCheckService and the TypeOrmHealthIndicator.

private readonly health: HealthCheckService,
private readonly database: TypeOrmHealthIndicator,

Finally, we should use the HealthCheckService, passing to it all the indicators we want, to determine the overall health. In this case, it will be just the database indicator.

check() {
  return this.health.check([() => this.database.pingCheck('database')]);
}

If you want to add more indicators, this doc shows all the available options, and examples of how to use some of them.

Commit - Adding health check

Last updated