如何自定义 Prisma 中间件实现软删除(soft delete)过滤?

解读

在国内一线/二线互联网公司的 Node 面试中,面试官抛出“软删除”话题,通常不是单纯问“加字段”这么简单,而是考察候选人对 Prisma 运行时(Query Engine)的掌控深度:

  1. 是否知道 Prisma Client 的 middleware 在“Query Engine → 数据库”之间插桩;
  2. 能否在不污染业务代码的前提下,把“过滤掉 deletedAt IS NOT NULL”的逻辑无感注入;
  3. 是否理解 middleware 只能改写 args(输入),不能改写 result(输出),因此“隐藏”已软删数据必须靠改写 where 条件;
  4. 对多表关联、嵌套查询、原生 SQL、事务、批量操作等极端场景是否有兜底方案。
    答不到“middleware 改写 args”这一层,基本会被判定为“只会用 ORM,不会扩展 ORM”。

知识点

  1. Prisma Client 初始化与 $use 注册顺序(先注册先执行,洋葱模型)。
  2. Prisma.Middleware 参数结构:params: { model, action, args, dataPath, runInTransaction }。
  3. 需要拦截的 action 白名单:'findUnique' | 'findFirst' | 'findMany' | 'update' | 'updateMany' | 'upsert' | 'delete' | 'deleteMany';
    其中 'delete'|'deleteMany' 要改写成 'update'|'updateMany' 并设置 deletedAt。
  4. 递归改写 args.where 的通用算法:遇到 AND/OR/NOT 数组要深度遍历,保证嵌套条件也能被注入。
  5. 事务与 runInTransaction=true 时 middleware 仍生效,但原生 SQL($queryRaw)不会触发 middleware,需要业务侧自律。
  6. 类型安全:通过 declare module '@prisma/client' { interface Model { deletedAt: Date | null } } 让 TypeScript 识别软删字段。
  7. 性能:middleware 是纯内存操作,不额外查库;但极端复杂 where 可能产生深拷贝,需要对象池或 LRU 做优化。
  8. 合规:国内 GDPR/《个人信息保护法》要求“可删除”,软删除只是业务标记,必须提供“硬删除”后台接口,middleware 需支持白名单绕过。

答案

以下示例基于 Prisma 5.x + MySQL8,展示一个可落地的“软删除中间件”最小闭环,支持:

  • 自动过滤已软删数据;
  • 把真实 delete 改为 update;
  • 支持手动绕过(force);
  • 兼容嵌套 where、事务、批量操作。
// prisma/softDelete.middleware.ts
import { Prisma, PrismaClient } from '@prisma/client';

const SOFT_DELETE_FIELD = 'deletedAt';

export function createSoftDeleteMiddleware(): Prisma.Middleware {
  return async (params: Prisma.MiddlewareParams, next: (params: Prisma.MiddlewareParams) => Promise<any>) => {
    const { model, action, args } = params;

    // 1. 模型白名单:只有包含 deletedAt 的模型才处理
    if (!args || !model) return next(params);

    // 2. 绕过开关:显式传 { includeDeleted: true } 则不过滤
    const includeDeleted = (args as any).includeDeleted === true;
    delete (args as any).includeDeleted;

    // 3. 拦截 delete -> update
    if (action === 'delete') {
      params.action = 'update';
      params.args = {
        ...args,
        data: { [SOFT_DELETE_FIELD]: new Date() },
      };
      return next(params);
    }
    if (action === 'deleteMany') {
      params.action = 'updateMany';
      params.args = {
        ...args,
        data: { [SOFT_DELETE_FIELD]: new Date() },
      };
      return next(params);
    }

    // 4. 查询类动作注入 where
    const readActions: Prisma.PrismaAction[] = ['findUnique', 'findFirst', 'findMany', 'update', 'updateMany', 'upsert'];
    if (!includeDeleted && readActions.includes(action)) {
      injectSoftDeleteWhere(args);
    }

    return next(params);
  };
}

// 递归注入 { deletedAt: null }
function injectSoftDeleteWhere(obj: any) {
  if (!obj.where) obj.where = {};
  const w = obj.where;

  // 如果顶层已存在 deletedAt 则尊重业务
  if (w[SOFT_DELETE_FIELD] !== undefined) return;

  // 处理 AND/OR/NOT
  if (Array.isArray(w.AND)) {
    w.AND.forEach(injectSoftDeleteWhere);
  } else if (Array.isArray(w.OR)) {
    w.OR.forEach(injectSoftDeleteWhere);
  } else if (Array.isArray(w.NOT)) {
    w.NOT.forEach(injectSoftDeleteWhere);
  }

  // 最终注入
  w[SOFT_DELETE_FIELD] = null;
}

注册方式:

// prisma/client.ts
import { PrismaClient } from '@prisma/client';
import { createSoftDeleteMiddleware } from './softDelete.middleware';

const prisma = new PrismaClient()
  .$extends({
    query: {
      $allModels: {
        // 扩展方法,支持 force 删除
        async forceDelete({ model, args, query }) {
          (args as any).includeDeleted = true;
          return (prisma as any)[model].delete(args);
        },
      },
    },
  })
  .$use(createSoftDeleteMiddleware());

export { prisma };

使用示例:

// 业务代码完全无感知
const users = await prisma.user.findMany(); // 自动过滤已软删
await prisma.user.delete({ where: { id: 1 } }); // 实际执行 update deletedAt=now()
await prisma.user.forceDelete({ where: { id: 2 } }); // 真正物理删除

拓展思考

  1. 关联模型级联软删:middleware 只能感知当前模型,若 Order 软删后需要级联 OrderItem,可在 Order 的 afterUpdate 钩子里用 $transaction 批量更新;或者把级联逻辑下沉到数据库层(触发器),但后者与 Prisma migrate 协同较麻烦。
  2. 多租户场景:deletedAt 需要与 tenantId 组合唯一索引,防止 A 租户误读 B 租户已软删数据;middleware 里同时注入 { tenantId: ctx.tenantId, deletedAt: null }。
  3. 灰度回滚:软删字段改为 deletedBy + deletedAt,middleware 同时写入操作人,方便审计;配合 ELK 做实时回收站。
  4. 性能调优:超深 where 递归可能造成 1~2 ms 开销,对万 QPS 服务可通过“编译缓存”把常见 where 模板序列化后存 LRU;或者改用 PostgreSQL 的 RLS(Row Level Security),把过滤逻辑下沉到数据库,middleware 仅负责设置 session 变量。
  5. 法律合规:国内用户注销账号必须“不可逆删除”,因此需提供“硬删除”后台接口并记录日志;middleware 通过 ctx.isAdmin && ctx.isLegalErase 白名单绕过,同时发 MQ 事件给风控系统。