Chris Bitoy
05/12/2022, 2:39 PMPrismaClient . 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:
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 learningNurul
05/12/2022, 2:58 PMPrismaClient 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:
import { PrismaClient } from '@prisma/client'
let prisma = new PrismaClient()
export default prisma
Here's an example in our official examples repo: graphql-expressChris Bitoy
05/12/2022, 3:03 PMChris Bitoy
05/12/2022, 4:06 PM./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?
./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;Nurul
05/13/2022, 8:30 AM