使用 Prisma 2 和 NestJS 进行日志记录 - 依赖注入问题?

问题描述

目前在我的第一个 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',{ level: 'error',],

然后像这样使用它:

@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 放在父级的超级中。它为我创造了奇迹。

希望对你有帮助;)

这是我的prismaService.ts

prisma.service.ts

import { INestApplication,Injectable,OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
    
    @Injectable()
    export class PrismaService extends PrismaClient implements OnModuleInit {
      constructor() {
        super({
          log: [
            { emit: 'event',level: 'query' },{ emit: 'stdout',level: 'info' },level: 'warn' },level: 'error' },],errorFormat: 'colorless',});
      }
      async onModuleInit() {
        await this.$connect();
      }
    
      async enableShutdownHooks(app: INestApplication) {
        this.$on('beforeExit',async (event) => {
          console.log(event.name);
          await app.close();
        });
      }
    }
@Injectable()
export class TestService {
  constructor(private prismaService: PrismaService) {
    prismaService.$on<any>('query',(event: Prisma.QueryEvent) => {
      console.log('Query: ' + event.query);
      console.log('Duration: ' + event.duration + 'ms');
    });
  }
}

Ps:我不得不删除dist文件夹并再次运行。

,

看起来像是 Prisma 客户端类型的问题。我建议您在 Prisma Github 存储库上打开一个问题。在此之前,您需要通过强制转换为 anyunknown

来忽略提供的类型