Search code examples
ormprisma

How to get the current model name or use other method at runtime in Prisma ORM


New feature has been included In prisma ORM version 4.9.0 Doc Link

After update schema.prisma as follow

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["clientExtensions"]
}

How do we get model name at runtime and use other method also at runtime

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

const db = new PrismaClient().$extends({
  client: {
    log: (s) => console.log(s),
    async useLog() {
      // how to use log function
      // here

    },
  },
  model: {
    $allModels: {
      log: (s) => console.log(s),
      async find(id, option = {}) {
        // how to get current model name in runtime
        
       // or use other function here
      },
    },
  },
});

module.exports = { db };

Solution

  • Here is the solution

    const { PrismaClient, Prisma } = require("@prisma/client");
    
    const db = new PrismaClient().$extends({
      client: {
        log: (s) => console.log(s),
        async useLog() {
          const ctx = Prisma.getExtensionContext(this);
          ctx.log("test"); // it will print "test" on console 
        },
      },
      model: {
        $allModels: {
          log: (s) => console.log(s),
          async find(id, option = {}) {
            const ctx = Prisma.getExtensionContext(this);
            // here is log the current runtime model name
            console.log(ctx.name);
    
            // here we can use other method of prisma model
            return ctx.findUniqueOrThrow({
              where: {
                id,
              },
              ...option,
            });
          },
        },
      },
    });
    
    module.exports = { db };
    
    

    Now we can use find method in all model just like

    const { db } = require("@app/src/utils/db");
    
    const teacher = await db.teacher.find(teacherId);
    const student = await db.student.find(studentId);