我正在使用 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 来说应该做什么。
您可以添加一个 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;
},
},
},
});
}