nest js 是否提供任何在保存、更新或删除后运行的内容,就像 django 信号提供的那样?

问题描述 投票:0回答:1

我正在使用 Nest js 和 prisma orm 运行一个项目。 假设我正在创建如下的帖子记录:


        // Query the database to create post -------------------------------------------------------
        try {
            post = await this.prisma.post.create({
                data: {
                    uuid: uuidv4(),
                    author: createPostDto.author,
                    categoryId: postCategory.id,
                    title: createPostDto.title,
                    content: createPostDto.content,
                    createdAt: new Date(),
                    updatedAt: new Date(),
                }
            })
        } catch (err) {
            this.logger.error(err);
            throw new InternalServerErrorException("Failed to create the post");
        }

创建记录后,我想运行一些特定的代码。假设我想通过调用

sendNotification()
方法向管理员发送通知。但我不想从 api 内部调用这个方法。

我知道 django 信号提供了类似的功能,可用于在创建、更新或删除行后运行代码的某些部分。但我不知道对于 Nest js 来说应该做什么。

python django nestjs prisma django-signals
1个回答
0
投票

您可以添加一个 Prisma 扩展,当您调用

prisma.post.create
时充当中间件。

您可以通过以下方式使用客户端扩展来实现 Prisma 服务:

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  async onModuleInit(): Promise<void> {
    await this.$connect();

    // Add the client extensions to the Prisma Client
    Object.assign(this, this.clientExtenstions);
  }

  clientExtenstions = this.$extends({
    query: {
      post: {
        async create({ args, query }) {
          // Execute the original query with the provided arguments
          const result = await query(args);

          // Send the email after the query was executed 
          // to ensure that the email only gets sent if the query was successful
          console.log("send mail");

          return result;
        },
      },
    },
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.