How to Use Prisma ORM Middlewares and Hooks?


How to Use Prisma ORM Middlewares and Hooks?

In today's modern web applications, it is extremely important to use an efficient and secure ORM (Object Relational Mapping) solution to interact with the database. Thanks to Prisma ORM middlewares and hooks, it is possible to add customizable controls and operations in database transactions. In this way, you can easily implement advanced features such as logging, authorization, or error handling in your application.

What is Prisma ORM Middleware?

Middleware works between the Prisma client and the database, allowing you to intervene before or after operations by processing the incoming request. In this way, during database operations, you can add steps such as validation, encryption, or logging before a transaction. These processes allow your application to be more secure and manageable.

Example of Middleware Usage

const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();

prisma.$use(async (params, next) => {
    if (params.action === "findMany") {
        console.log(`Model: ${params.model}, Operation: ${params.action}`);
    }
    return next(params);
});

async function getUsers() {
    const users = await prisma.user.findMany();
    console.log(users);
}

getUsers();

In the example above, we log the model and operation on every findMany call. With this mechanism, both logging and security controls can be practically added.

What are Prisma ORM Hooks?

There are no hooks (predefined event triggers) in Prisma ORM in the classical sense. However, the middleware structure allows you to capture CRUD operations by acting like hooks. In addition, thanks to the programming patterns used with @prisma/client, you can programmatically create after/before logic.

How is a Common Hook (Before/After Save) Written?

prisma.$use(async (params, next) => {
    // Before Save Hook
    if (params.action === "create" && params.model === "User") {
        params.args.data.createdAt = new Date();
        params.args.data.updatedAt = new Date();
    }
    const result = await next(params);
    // After Save Hook
    if (["create", "update"].includes(params.action) && params.model === "User") {
        console.log("User record has been updated or created.");
    }
    return result;
});

In this example, we both set the date fields before the user is created (before save), and notify with console.log after the operation is successful.

Conclusion

Thanks to Prisma ORM middlewares and hooks, you can have full control over database operations in Node.js projects, and easily add security and traceability. Using the concepts of Prisma ORM middlewares and hooks correctly and effectively ensures your modern applications are sustainable and easy to maintain. With these structures, you can get rid of repetitive code and add quality to your application.