notiz-dev / nestjs-prisma

Easy Prisma support for your NestJS application
https://nestjs-prisma.dev
MIT License
587 stars 50 forks source link

How to configure when using CustomPrismaModule.forRootAsync #96

Closed JinJieBeWater closed 6 months ago

JinJieBeWater commented 6 months ago

How to configure when using CustomPrismaModule.forRootAsync, for example prismaServiceOptions: { middlewares: [loggingMiddleware()] }, image

marcjulian commented 6 months ago

Hey @JinJieBeWater, because you have full control over the PrismaClient instance you need to pass the middleware before using $extends. Here is an example, maybe a good idea to add it to the docs.

// prisma.extension.ts
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

// apply middleware with `$use` 👇
prisma.$use(loggingMiddleware());
prisma.$use(...); // as many as you want

// now extend the PrismaClient
export const extendedPrismaClient = prisma
  .$extends({
    model: {
      user: {
        findByEmail: async (email: string) => {
          console.log('extension findByEmail');
          return extendedPrismaClient.user.findFirstOrThrow({
            where: { email },
          });
        },
      },
    },
  })

export type ExtendedPrismaClient = typeof extendedPrismaClient;

// app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

import { CustomPrismaModule } from 'nestjs-prisma';
import { extendedPrismaClient } from './prisma.extension';

@Module({
  imports: [
    CustomPrismaModule.forRootAsync({
      name: 'PrismaService',
      useFactory: () => {
        return extendedPrismaClient;
      },
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
marcjulian commented 6 months ago

On this note, Prisma deprecated middleware in favor of extensions query. Maybe it would be good to provide the loggingMiddleware also as loggingExtension. Prisma has an example of the query logging as extension: https://github.com/prisma/prisma-client-extensions/tree/main/query-logging.

Let me know what you think and if the above works for you.

JinJieBeWater commented 6 months ago

On this note, Prisma deprecated middleware in favor of extensions query. Maybe it would be good to provide the loggingMiddleware also as loggingExtension. Prisma has an example of the query logging as extension: https://github.com/prisma/prisma-client-extensions/tree/main/query-logging。在这一点上,Prisma弃用中间件,支持扩展查询。也许这将是很好的提供 loggingMiddleware 也为 loggingExtension 。Prisma有一个查询日志作为扩展的示例: https://github.com/prisma/prisma-client-extensions/tree/main/query-logging

Let me know what you think and if the above works for you.让我知道你的想法,如果上面为你工作。

Oh, thank you for taking the time to help me, using extensions query is a good idea, I learned a lot, maybe I should look at these examples again, my problem has been solved, thank you for your help