Good day <@U024DS62DRC> , I just got out of a meet...
# orm-help
c
Good day @Nurul , I just got out of a meeting with my manager who corrected me about how I set up my
PrismaClient
. Although I didn’t quite agree because I have seen online people (including folks at Prisma) set it up the same way I did on multiple tutorial videos. I usually set it up like this in every single file that I needed to use Prisma:
Copy code
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
However, he insisted that
"the best practice is to create the prisma client once and import it - this way you're not recreating database connections if multiple files use prisma, etc"
Can you advice on how best to set it up - still learning
1
n
Hey Chris 👋 The number of
PrismaClient
instances matter, Your application should generally only create one instance of
PrismaClient
The reason for this is that each instance of
PrismaClient
manages a connection pool, which means that a large number of clients can exhaust the database connection limit. How to achieve this depends on whether you are using Prisma in a long-running application or in a serverless environment For long running application like in an express app, you should create a module that exports
PrismaClient
object and then import it in other files Like this:
Copy code
import { PrismaClient } from '@prisma/client'

let prisma = new PrismaClient()

export default prisma
Here's an example in our official examples repo: graphql-express
c
I see. Thanks 🙏
Thanks again @Nurul, its becoming clearer to me now (slowly but surely). So this code:
Copy code
./data.js
import { PrismaClient } from '@prisma/client';

const ArtData = async (req, res) => {
  const prisma = new PrismaClient({ log: ['query'] }); //This line is replace below

  try {
    
  } catch (error) {
    console.error(error);
    res.status(500);
    res.json({ error: 'something went wrong', error });
  } finally {
    await prisma.$disconnect();
  }
};

export default ArtData;
Can be re-written as this?
Copy code
./data.js
import {prisma} from '../../../lib/prisma';

const ArtData = async (req, res) => {
  prisma({ log: ['query'] }) //replaced the above

  try {
    
  } catch (error) {
    console.error(error);
    res.status(500);
    res.json({ error: 'something went wrong', error });
  } finally {
    await prisma.$disconnect();
  }
};

export default ArtData;
👍 2
n
That’s correct