目前在我的第一个 NestJS 项目中。我正在使用 Prisma 2,并希望以调试模式将查询记录到控制台,以学习和检查并避免 n+1 等!
我创建了 prisma.service.ts
:
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common'
import { PrismaClient } from '@prisma/client'
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
constructor() {
super();
}
async onModuleInit() {
await this.$connect()
}
async onModuleDestroy() {
await this.$disconnect()
}
}
工作正常,我可以在 API 中使用它并访问数据库。但是,根据 Logging 上的 Prisma 2 Docs,我需要通过
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient({
log: [
{ level: 'warn', emit: 'event' },
{ level: 'info', emit: 'event' },
{ level: 'error', emit: 'event' },
],
然后像这样使用它:
@Injectable()
export class TestService {
constructor(private prismaService: PrismaService) {
this.prismaService.$on('query', e => {
console.log("Query: " + e.query)
console.log("Duration: " + e.duration + "ms")
})
}
可悲的是,在编译时,我得到了这些错误:
TSError: ⨯ Unable to compile TypeScript:
src/test.service.ts:9:31 - error TS2345: Argument of type '"query"' is not assignable to parameter of type '"beforeExit"'.
9 this.prismaService.$on('query', e => {
~~~~~~~
src/test.service.ts:10:39 - error TS2339: Property 'query' does not exist on type '() => Promise<void>'.
10 console.log("Query: " + e.query)
~~~~~
src/test.service.ts:11:42 - error TS2339: Property 'duration' does not exist on type '() => Promise<void>'.
11 console.log("Duration: " + e.duration + "ms")
我尝试将 log
数组传递到服务中的 super()
中,但没有任何运气。
我只是缺少一些小东西吗?
嘿兄弟,我一直在使用 prima 2 + nestjs,我把配置 prima 放在父级的 super 中,就像这样。它为我创造了奇迹。
我希望它对你有帮助;)
这是我的 prismaService.ts
prisma.service.ts
Ps:我不得不删除dist文件夹并再次运行。