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

如何在NestJS中使用第二个Prisma客户端?遇测试及TS错误

解决NestJS多Prisma客户端E2E测试及TypeScript类型问题

一、解决E2E测试"Cannot find module '../../prisma2/generated/client2'"错误

  • 确认第二个Prisma Schema的生成配置:在prisma2/schema.prisma中确保output路径正确:
    generator client2 {
      provider = "prisma-client-js"
      output   = "./generated/client2"
    }
    
    执行npx prisma generate --schema=./prisma2/schema.prisma,验证prisma2/generated/client2文件夹是否生成。
  • 修正测试文件中的相对路径:E2E测试文件通常在test/目录下,原相对路径../../prisma2/...需调整为../prisma2/generated/client2,或用绝对路径避免路径混乱:
    import { PrismaClient as PrismaClient2 } from path.join(process.cwd(), 'prisma2/generated/client2');
    
  • 确保测试前自动生成客户端:修改package.json的E2E测试脚本,添加生成命令:
    "scripts": {
      "test:e2e": "prisma generate --schema=./prisma2/schema.prisma && jest --config ./test/jest-e2e.json"
    }
    

二、解决"Cannot use namespace 'NodeJS' as a value"及"Namespace 'NodeJS' has no exported member 'Global'"错误

  • 替换NodeJS.Global为globalThis:如果代码中是在全局缓存Prisma客户端,将原有代码:
    const client2 = (global as NodeJS.Global).prisma2 || new PrismaClient2();
    if (process.env.NODE_ENV !== 'production') (global as NodeJS.Global).prisma2 = client2;
    
    修改为:
    const client2 = (globalThis as any).prisma2 || new PrismaClient2();
    if (process.env.NODE_ENV !== 'production') (globalThis as any).prisma2 = client2;
    
  • 添加自定义全局类型声明:在src/目录下创建global.d.ts文件,定义全局变量类型:
    declare global {
      var prisma2: import('../prisma2/generated/client2').PrismaClient;
    }
    export {};
    
  • 调整TypeScript配置:确保tsconfig.json的compilerOptions中包含"types": ["node"],并安装对应版本的@types/node(如Node版本为18.x,执行npm install @types/node@18 --save-dev)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:17:11