You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用@nestjs/terminus实现Prisma自定义健康检查

你复用Mongoose健康检查的逻辑存在适配错误,这是报错的直接原因:getConnectionToken 是@nestjs/mongoose 包提供的工具方法,用于获取Mongoose连接实例的注入token,Prisma本身以及官方NestJS Prisma集成均不提供该方法,你从prisma包中读取该属性必然为undefined,生成的注入token无效,自然无法从Nest容器中获取到Prisma连接实例。

正确实现自定义Prisma健康检查

步骤1:明确Prisma实例的注入规则

常规NestJS项目中,Prisma实例都是以PrismaService为token注册到容器中的,不管你是自定义的继承PrismaClient的服务,还是使用@nestjs/prisma包提供的内置服务,均遵循这个规则。

步骤2:修改健康检查逻辑

你可以直接调整getContextConnection方法,改为直接获取PrismaService实例即可:

import { Injectable, ModuleRef } from '@nestjs/common';
import { HealthIndicator, HealthIndicatorResult, HealthCheckError } from '@nestjs/terminus';
import { PrismaService } from './prisma.service'; // 替换为你实际的PrismaService路径

@Injectable()
export class PrismaHealthIndicator extends HealthIndicator {
  constructor(private moduleRef: ModuleRef) {
    super();
  }

  async pingCheck(key: string, options?: { connection?: PrismaService }): Promise<HealthIndicatorResult> {
    const connection = options.connection || this.getContextConnection();

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

    try {
      // 执行简单查询验证连接可用性
      await connection.$queryRaw`SELECT 1`;
      return this.getStatus(key, true);
    } catch (e) {
      throw new HealthCheckError(
        'Prisma health check failed',
        this.getStatus(key, false, {
          message: e.message,
        }),
      );
    }
  }

  private getContextConnection(): PrismaService | null {
    try {
      // 直接获取PrismaService实例,不需要额外生成token
      return this.moduleRef.get(PrismaService, {
        strict: false,
      });
    } catch (err) {
      return null;
    }
  }
}

排查注意事项

  • 确认你的PrismaService所在的模块已被健康检查模块导入,或者PrismaService是全局注册的Provider
  • 如果你希望简化实现,可以直接在健康检查Controller中注入PrismaService,不需要单独自定义HealthIndicator,直接调用$queryRaw验证连接即可。

内容的提问来源于stack exchange,提问作者zedian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 08:36:05