How we can add prisma middleware in different file?

936 Views Asked by At

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

1

There are 1 best solutions below

1
Mradul Jain On BEST ANSWER

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)
})