Prisma Issue of managing instances of Prisma Client actively running

Viewed 1064

I'm new to Prisma and Nodejs

I accidentally created lots of instances of Prisma Client that keep displaying the warning of

warn(prisma-client) There are already 10 instances of Prisma Client actively running.

Even I tried to delete old files and create a new Prisma, it keep showing the same warning.

I was wondering is there any way to clear the duplicated instances that already actively running?

I found a lot of INFO only about to prevent the situation occur instead of clearing it.

Node js version.        : v14.18.2
NPM version.            : 6.14.15
prisma                  : 3.7.0
@prisma/client          : 3.7.0

Thank you for your help.

2 Answers

So the problem is that you are probably creating a new PrismaClient() every time you need to use it. The ideal would be to instantiate it once and only use that instance. In the docs they recommend it in this way

If you are in a serverless env, you can try this code as well:

import { PrismaClient } from "@prisma/client";

declare global {
  namespace NodeJS {
    interface Global {
      prisma: PrismaClient;
    }
  }
}

let prisma: PrismaClient;

if (!global.prisma) {
  global.prisma = new PrismaClient({
    log: ["info"],
  });
}
prisma = global.prisma;

export default prisma;

the problem is that you are probably creating a new PrismaClient()

you can use singleTon pattern to solve it ,(I'm use typescript here !)

import { PrismaClient } from '@prisma/client'

export class Prisma {
    public static Prisma :PrismaClient ;
    
    static  getPrisma (){
      //verify if prisma instance not exist
        if (this.Prisma===null || !this.Prisma)
      //create new one
            this.Prisma=new PrismaClient()
        return this.Prisma
    }
}
Related