Search code examples
nestjsprismahealth-check

How to create a custom health check for Prisma with @nestjs/terminus?


Since @nestjs/terminus doesn't provide a health check for Prisma, I'm trying to create it based on their Mongoose health check.

When I try:

import * as Prisma from 'prisma';
...
...
  private getContextConnection(): any | null {
    const {
      getConnectionToken,
      // eslint-disable-next-line @typescript-eslint/no-var-requires
    } = require('prisma') as typeof Prisma;

    try {
      return this.moduleRef.get(getConnectionToken('DatabaseConnection') as string, {
        strict: false,
      });
    } catch (err) {
      return null;
    }
  }
...
...
    const connection = options.connection || this.getContextConnection();

    if (!connection) {
      throw new ConnectionNotFoundError(
        this.getStatus(key, isHealthy, {
          message: 'Connection provider not found in application context',
        }),
      );
    }

I always seem to get: "message": "Connection provider not found in application context". There is a problem with the connection or I don't really understand how the health check actually works


Solution

  • A naive copy of the mongoose implementation isn't going to work because there are differences between the NestJSMongoose type/module and Prisma. In particular, getConnectionToken does not exist inside the Prisma package.

    I can't comment on what the best way would be to extend terminus to support prisma. You might have to dig a bit into the terminus interface for that. However, a simple way to get a health check/ping in Prisma is to use the following query:

        prisma.$queryRaw`SELECT 1`