如何使用 @nestjs/terminus 为 Prisma 创建自定义健康检查?

zed*_*ian 8 nestjs prisma health-check

由于@nestjs/terminus不为 Prisma 提供健康检查,我尝试根据他们的Mongoose 健康检查创建它。

当我尝试时:

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',
        }),
      );
    }
Run Code Online (Sandbox Code Playgroud)

我似乎总是收到:“消息”:“在应用程序上下文中找不到连接提供程序”。连接有问题或者我不太明白健康检查的实际工作原理

Jef*_*ley 10

这个问题帮助我为 NestJS 构建了 Prisma 健康检查。

这是我做的:

import { Injectable } from "@nestjs/common";
import { HealthCheckError, HealthIndicator, HealthIndicatorResult } from "@nestjs/terminus";
import { PrismaService } from "./prisma.service";

@Injectable()
export class PrismaHealthIndicator extends HealthIndicator {
  constructor(private readonly prismaService: PrismaService) {
    super();
  }

  async isHealthy(key: string): Promise<HealthIndicatorResult> {
    try {
      await this.prismaService.$queryRaw`SELECT 1`;
      return this.getStatus(key, true);
    } catch (e) {
      throw new HealthCheckError("Prisma check failed", e);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这将PrismaService完全按照 NestJS 文档中显示的方式注入 a 。https://docs.nestjs.com/recipes/prisma#use-prisma-client-in-your-nestjs-services

您也可以替换prismaServicenew PrismaClient().


Tas*_*mam 5

猫鼬实现的简单副本是行不通的,因为类型NestJSMongoose/模块和Prisma. 特别是,包getConnectionToken内不存在Prisma

我无法评论扩展终点站以支持 prisma 的最佳方法是什么。terminus为此,您可能需要深入研究一下界面。然而,在 Prisma 中获取运行状况检查/ping 的一个简单方法是使用以下查询:

    prisma.$queryRaw`SELECT 1`
Run Code Online (Sandbox Code Playgroud)