notiz-dev / nestjs-prisma

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

call prismaService inside middleware? #53

Closed conioX closed 1 year ago

conioX commented 1 year ago

Hi, there is a way i can excecute query inside a middleware or how to call prismaService inside the middleware?

AienTech commented 1 year ago

~also interested in the answer...~

Ah, that was quite easy to solve. For future readers:

first, define the prisma service:

import { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';
import { Prisma, PrismaClient } from '@prisma/client';

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

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

    public addUserToFilter(params: Prisma.MiddlewareParams) {
        console.log(params);
    }
}

then define a module that exports this service:

import { Module } from '@nestjs/common';
import { PrismaService } from './prisma.service';

@Module({
    providers: [PrismaService],
    exports: [PrismaService],
})
export class PrismaModule { }

then use this example to register and use your service:

import { Module } from '@nestjs/common';
import { PrismaModule } from 'nestjs-prisma';
import { PrismaModule as PrismaCustomModule } from '@/config/prisma/prisma.module';
import { PrismaService } from '@/config/prisma/prisma.service';

@Module({
    imports: [
        PrismaCustomModule,
        PrismaModule.forRootAsync({
            isGlobal: true,
            inject: [PrismaService],
            imports: [PrismaCustomModule],
            useFactory: async (prismaService: PrismaService) => ({
                prismaOptions: {
                    log: ['info', 'query'],
                },
                explicitConnect: false,
                middlewares: [
                    async (params, next) => {
                        prismaService.addUserToFilter(params);
                        const result = await next(params);
                        return result;
                    },
                ],
            }),
        }),
    ],
})
export class AppModule { }

cheers to you future reader, and best wishes

marcjulian commented 1 year ago

I will close this issue. I think the suggestion from @AienTech should work.