I am trying to use Prisma middleware to hash passwords. For hashing, I created a new directory (middleware) and created a new file prisma.ts inside it. Now I want to access these middleware, whenever a new user is created.
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)
})
您可以在您创建的新文件中导入prisma
,然后在那里定义您的中间件。
// File: prisma.ts
import { PrismaClient, Prisma } from '@prisma/client'
import * as middleware from './prismaMiddleware';
const prisma: PrismaClient = new PrismaClient();
prisma.$use(middleware.Encrypt);
// File: prismaMiddleware.ts
import {Prisma} from '@prisma/client';
import bcrypt from 'bcryptjs';
export const Encrypt: Prisma.Middleware = 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)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.