Skip to content

Instantly share code, notes, and snippets.

@link-boris
Created October 14, 2022 21:17
Show Gist options
  • Save link-boris/fe7320d932ff53921dcc8cfdfcfd2c1c to your computer and use it in GitHub Desktop.
Save link-boris/fe7320d932ff53921dcc8cfdfcfd2c1c to your computer and use it in GitHub Desktop.
Prisma Client Setup + Middleware for soft deletes
import { PrismaClient } from '@prisma/client'
const dbClient = new PrismaClient({})
/*
* Middleware to replace hard deletes with soft deletes
* 1. deletes will update deletedAt column
* 2. finds and updates will filter out deletedAt rows
*/
dbClient.$use(async (params, next) => {
params.args = params.args || {}
const addDeletedAtTimestamp = (data = {}) => ({
...data,
deletedAt: new Date(),
})
const removeSoftDeleteFromWhere = (where = {}) => ({
...where,
deletedAt: { equals: null },
})
switch (params.action) {
case 'delete':
params.action = 'update'
params.args.data = addDeletedAtTimestamp(params.args.data)
break
case 'deleteMany':
params.action = 'updateMany'
params.args.data = addDeletedAtTimestamp(params.args.data)
break
case 'findUnique':
case 'findFirst':
params.action = 'findFirst'
params.args.where = removeSoftDeleteFromWhere(params.args.where)
break
case 'findMany':
params.args.where = removeSoftDeleteFromWhere(params.args.where)
break
}
return next(params)
})
export const db = dbClient
handlePrismaLogging({ db })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment