Created
October 14, 2022 21:17
-
-
Save link-boris/fe7320d932ff53921dcc8cfdfcfd2c1c to your computer and use it in GitHub Desktop.
Prisma Client Setup + Middleware for soft deletes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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