Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 30 additions & 19 deletions src/config/prisma.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,38 @@
const { PrismaClient } = require("@prisma/client");
const { PrismaPg } = require("@prisma/adapter-pg");
const { Pool } = require("pg");

const path = process.env.NODE_ENV === "test" ? "tests/.env.test" : ".env";
require("dotenv").config({ path, override: false });

/**
* PostgreSQL connection pool.
* Explicit pool management is required in Prisma 7.
*/
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});

/**
* Prisma Client singleton.
*
* - Uses pg driver explicitly (Prisma 7+)
* - Avoids multiple connections
* - Centralizes database access
*/
const prisma = new PrismaClient({
adapter: new PrismaPg(pool),
log: ["error", "warn"],
});
const globalForPrisma = globalThis;

if (!globalForPrisma.__authApiPool) {
globalForPrisma.__authApiPool = new Pool({
connectionString: process.env.DATABASE_URL,
});
}

if (!globalForPrisma.__authApiPrisma) {
globalForPrisma.__authApiPrisma = new PrismaClient({
adapter: new PrismaPg(globalForPrisma.__authApiPool),
log: ["error", "warn"],
});
}

const pool = globalForPrisma.__authApiPool;
const prisma = globalForPrisma.__authApiPrisma;

let isClosing = false;
async function closePrismaConnection() {
if (isClosing) return;
isClosing = true;

await prisma.$disconnect();
await pool.end();

isClosing = false;
}

module.exports = prisma;
module.exports.closePrismaConnection = closePrismaConnection;
3 changes: 2 additions & 1 deletion tests/setup.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const prisma = require("../src/config/prisma.ts");
const { closePrismaConnection } = require("../src/config/prisma.ts");
const { closeRedisConnection } = require("../src/config/redis.ts");

beforeEach(async () => {
Expand All @@ -8,5 +9,5 @@ beforeEach(async () => {

afterAll(async () => {
await closeRedisConnection();
await prisma.$disconnect();
await closePrismaConnection();
});