prismaprisma2

Instantiate prisma only once


I am currently using prisma 2.20.1 on a project running postgres.

On their doc they say to import PrismaClient and instantiate it throughout the application.

However, coming from other use cases, where you connect to the db only once, feels weird on every route (different file and directory as my project structure is set to), to instantiate, and (connect to the db again?).

My point is, is there a way to centralize the database connection in one file, and use its instance throughout the application? Would it be safe to do that? Any consequences?

My idea is something like:

// database.ts
import { PrismaClient } from '@prisma/client';

class Database {
    constructor() {
        this.db = new PrismaClient();
    }
}

const database = new Database();

export default new Database();

Then across the routes files

// specificRouteFile.ts
import db from 'database';

// run queries...
db.SomeTable.create({})

Solution

  • You can create and initialize Prisma in a file and then import it across the different files.

    //lib/prisma.js
    import { PrismaClient } from "@prisma/client";
    
    const prisma = new PrismaClient();
    
    export default prisma;
    
    

    Then in a different file for example, just do

    import prisma from "./lib/prisma"
    
    const posts = prisma.posts.findMany({})