middlewareprismaprism-4

How we can add prisma middleware in different file?


I have multiple middleware for a single route. can i breakdown code and move middleware in different file?.I tried with import a middleware in server file but it is not working


Solution

  • try to add like these

    import bcrypt from 'bcryptjs'
    import { PrismaClient, Prisma } from '@prisma/client'
    
    const prisma: PrismaClient = new PrismaClient()
    
    prisma.$use(async (params: Prisma.MiddlewareParams, next) => {
        if (params.action == 'create' && params.model == 'User') {
            let user = params.args.data
            let salt = bcrypt.genSaltSync(10)
            let hash = bcrypt.hashSync(user.password, salt)
            user.password = hash
        }
        return await next(params)
    })