NodeJS 如何在NestJs中使用第二个Prisma客户端?

b4wnujal  于 2023-03-29  发布在  Node.js
关注(0)|答案(1)|浏览(164)

我尝试在我的项目中使用第二个Prisma客户端:

下面是Prisma的Client.ts:

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  async onModuleInit() {
    await this.$connect();
  }

  async enableShutdownHooks(app: INestApplication) {
    this.$on('beforeExit', async () => {
      await app.close();
    });
  }
}

以下是Prisma2的Client2.ts:

const { PrismaClient } = require('../../prisma2/generated/client2');
interface CustomNodeJsGlobal {
  prisma2: typeof PrismaClient;
}
declare const global: CustomNodeJsGlobal;
const prisma2 = global.prisma2 || new PrismaClient();
if (process.env.NODE_ENV === 'development') {
  global.prisma2 = prisma2;
}
prisma2.$on('beforeExit', async () => {
  console.log('beforeExit hook');
  // PrismaClient still available
  await prisma2.$disconnect();
});
export default prisma2;

我可以使用上面的配置运行我的项目并访问数据库(prisma和prisma2)。但是,如果我运行e2e测试,我会得到以下错误:

Cannot find module '../../prisma2/generated/client2' from '../src/client2.ts'

我将Client2.ts重写为:

import { PrismaClient as PrismaClient2 } from '../prisma2/generated/client2';
interface CustomNodeJsGlobal extends NodeJS.Global {
  prisma2: PrismaClient2;
}

// Prevent multiple instances of Prisma Client in development
declare const global: CustomNodeJsGlobal;

const prisma2 =
  global.prisma2 ||
  new PrismaClient2({
    log: ['query'],
  });

if (process.env.NODE_ENV === 'dev') global.prisma2 = prisma2;

export default prisma2;

这会让我:

Cannot use namespace 'NodeJS' as a value
Namespace 'NodeJS' has no exported member 'Global'
wqsoz72f

wqsoz72f1#

尝试添加您的tsconfig

"types": [
  "node"
]

并在devDependency版本中添加@types/node@x.x.x.x

相关问题