Search code examples
nestjsprisma

how to do Prisma soft delete with NestJS?


I had tried to implement this method in my application. but I don't have depth knowledge of Prisma. Kindly explain that with some examples.


Solution

  • You can write a middleware to mark a question as a deleted instead of actually deleting it.

    schema.prisma

    datasource db {
      provider = "postgresql"
      url      = env("DATABASE_URL")
    }
    
    generator client {
      provider = "prisma-client-js"
    }
    
    model Post {
      id      Int     @id @default(autoincrement())
      title   String
      content String?
      user    User?   @relation(fields: [userId], references: [id])
      userId  Int?
      tags    Tag[]
      views   Int     @default(0)
      deleted Boolean @default(false)
    }
    

    Here a field called deleted is added to the Post model.

    Middleware performs the following operation:

    • Intercepts delete and deleteMany queries for the Post model
    • Changes the params.action to update and updateMany respectively
    • Introduces a data argument and sets { deleted: true }, preserving other filter arguments if they exist

    script.ts

    
    import { PrismaClient } from '@prisma/client'
    
    const prisma = new PrismaClient({})
    
    async function main() {
      /***********************************/
      /* SOFT DELETE MIDDLEWARE */
      /***********************************/
    
      prisma.$use(async (params, next) => {
        // Check incoming query type
        if (params.model == 'Post') {
          if (params.action == 'delete') {
            // Delete queries
            // Change action to an update
            params.action = 'update'
            params.args['data'] = { deleted: true }
          }
          if (params.action == 'deleteMany') {
            // Delete many queries
            params.action = 'updateMany'
            if (params.args.data != undefined) {
              params.args.data['deleted'] = true
            } else {
              params.args['data'] = { deleted: true }
            }
          }
        }
        return next(params)
      })