Hello everyone. I am trying to fix an issue involv...
# orm-help
s
Hello everyone. I am trying to fix an issue involving SSR, ts and multiple prisma instances. I have read the different Github issues opened, but none of the solutions work in my - edge - case. Here is the code initializing Prisma:
Copy code
import { PrismaClient } from '@prisma/client';

export let prisma: PrismaClient;

if (typeof window === 'undefined') {
  if (process.env['NODE_ENV'] === 'production') {
    prisma = new PrismaClient();
  } else {
    /* eslint-disable @typescript-eslint/ban-ts-comment */
    // @ts-ignore
    if (!global.prisma) {
      // @ts-ignore
      global.prisma = new PrismaClient();
    }
    // @ts-ignore
    prisma = global.prisma;
  }
}
This works okay bar from the ugly ts-ignores, which I would like to remove. I can fix this by prepending the code above with:
Copy code
declare global {
  var prisma: PrismaClient
}
But then it clashes with Jest which throws a
Duplicate declaration "prisma" error
.
What would be the correct way of fixing this, without exporting prisma as default ? Why is Jest confused by this? (I am not sure about the error, seems like Jest is unable to infer that this is the same variable).
✅ 1
l
I use to have Prisma in Next.js and something like this worked for me:
Copy code
import { PrismaClient } from "@prisma/client";

// Prevent multiple instances of Prisma Client in development
declare const global: Global & { prisma?: PrismaClient };

export const prisma =
  global.prisma ||
  new PrismaClient({
    log:
      process.env.NODE_ENV === "production"
        ? ["error"]
        : ["error", "info", "warn"],
  });
if (process.env.NODE_ENV === "development") global.prisma = prisma;
🚀 1
s
I am not sure why declaring this way fixed my problem but it did. Seems like setting prisma as a var in declare was confusing Jest. Thank you very much!
👍 2
n
I feel the same way should just have the best practices as the same as Prisma’s connection management one question @Lloyd Richards should the prisma declare parameter be optional? The reason I ask is prisma docs dont have it as optional and im just curious whats the correct way below is prisma optional remove of what I’m speaking of.
declare const global: Global & { prisma: PrismaClient };
l
I believe its optional because when your in dev with Next.js the auto refresh can cause hundreds of prisma clients to be created in the background. By having it optional, and then checking if it exists, you make sure only one instance of prisma client is running. This maybe matters less in prod