Does nest js provide anything that runs after saving, updating or deleting, like how django signals provides?

82 Views Asked by At

I am running a project with nest js and prisma orm. Suppose I am creating a post record like following:


        // 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");
        }

After creating a record I want to run some perticular code. suppose I want to send notification to admins by calling sendNotification() method. But I don't want to call this method from inside an api.

I know that django signals provide similar feature that can be used to run some part of code after creating, updating, or deleting a row. But I don't know what should be aprropeiate in the case of nest js.

1

There are 1 best solutions below

0
stonith404 On

You could add a Prisma extension that acts as a middleware when you call prisma.post.create.

Here’s how you can implement a Prisma Service with a client extension for this purpose:

@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;
        },
      },
    },
  });
}