#define instance in global? i didn't get this.

5 messages · Page 1 of 1 (latest)

neat dawn
#

i created repository for the DB. but i found something dubious, he define defined the instance of prisma in global context. but why?

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

export const prisma = global.prisma || new PrismaClient();

if (process.env.NODE_ENV !== "production") global.prisma = prisma;

export * from "@prisma/client";
odd drum
#

i've never used prisma, but my guess is new PrismaClient() is expensive and they want to make sure it's only ever done once during the lifecycle of the program

#

as for the weird !== "production" check, maybe they're thinking specifically about hot reloading causing the client to be reinitialized? ¯_(ツ)_/¯

raven sail
# odd drum i've never used prisma, but my guess is `new PrismaClient()` is expensive and th...

when using next dev, Next clears the cache of Node.js, which causes a re-instantiate of the Prisma client. Together, hot reloading causes more connection pools. Using a global context, when restarted, it creates asigle instance Prisma and saves it globally context object. If Prisma exists in the global context, it just uses the Prisma instance from the global context instead of re-instantiating the class.