【问题标题】:Where is the beest place to put prisma middleware on NestJs?在 NestJs 中放置 prisma 中间件的最佳位置在哪里?
【发布时间】:2021-12-03 11:32:45
【问题描述】:

我的 prisma.service.ts 看起来像这样:

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  async onModuleInit() {
    await this.$connect();
  }

  async enableShutdownHooks(app: INestApplication) {
    this.$on('beforeExit', async () => {
      await app.close();
    });
  }
}

根据Prisma docs,我应该将它们放在请求处理程序的上下文之外。这就是我在 ma​​in.ts 上创建的应用程序。在定义应用程序本身之前将中间件放在那里对我来说看起来很奇怪并且不起作用。我更愿意将它放在 prisma.service.ts 文件本身

【问题讨论】:

  • 在这种情况下,理想情况下它将位于 onModuleInit 内。还要确保PrismaService 在整个应用程序中只创建了一个实例。多个实例意味着多个中间件,这可能会导致问题。

标签: nestjs prisma


【解决方案1】:

不确定这是否是注册它们的“最佳”位置,但我们在服务的构造函数中与日志配置一起进行,并且它可以工作:

import { INestApplication, Injectable, Logger, OnModuleInit } from "@nestjs/common";
import { Prisma, PrismaClient } from "@prisma/client";
import { ConcurrencyErrorMiddleware } from "./concurrency-error.middleware";

@Injectable()
export class PrismaService extends PrismaClient<Prisma.PrismaClientOptions, "query"> implements OnModuleInit {
  private readonly logger = new Logger(PrismaService.name);

  constructor() {
    super({ log: [{ emit: "event", level: "query" }] });

    this.logger.log(`Prisma v${Prisma.prismaVersion.client}`);
    this.$on("query", (e) => this.logger.debug(`${e.query} ${e.params}`));

    this.$use(ConcurrencyErrorMiddleware());
  }

  async onModuleInit(): Promise<void> {
    await this.$connect();
  }

  async enableShutdownHooks(app: INestApplication): Promise<void> {
    this.$on("beforeExit", async () => {
      await app.close();
    });
  }
}
// An example of such a middleware.
import { Prisma } from "@prisma/client";

export function ConcurrencyErrorMiddleware<T extends Prisma.BatchPayload = Prisma.BatchPayload>(): Prisma.Middleware {
  return async (params: Prisma.MiddlewareParams, next: (params: Prisma.MiddlewareParams) => Promise<T>): Promise<T> => {
    const result = await next(params);
    if (
      (params.action === "updateMany" || params.action === "deleteMany") &&
      params.args.where.version &&
      result.count === 0
    ) {
      throw new ConcurrencyError();
    }
    return result;
  };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多