mirror of
https://github.com/kjanat/livedash-node.git
synced 2026-02-13 22:15:45 +01:00
- Make Prisma client initialization lazy via Proxy - Defer database-pool import until runtime - Add guard for empty DATABASE_URL - Build now succeeds with Next.js 16.1.4
74 lines
2.1 KiB
TypeScript
74 lines
2.1 KiB
TypeScript
// Enhanced Prisma client setup with connection pooling
|
|
import { PrismaClient } from "@prisma/client";
|
|
|
|
// Add prisma to the NodeJS global type
|
|
declare const global: {
|
|
prisma: PrismaClient | undefined;
|
|
};
|
|
|
|
// Lazy-load createEnhancedPrismaClient to avoid build-time URL parsing
|
|
const createPrismaClient = () => {
|
|
// Use enhanced pooling in production or when explicitly enabled
|
|
const useEnhancedPooling =
|
|
process.env.NODE_ENV === "production" ||
|
|
process.env.USE_ENHANCED_POOLING === "true";
|
|
|
|
if (useEnhancedPooling) {
|
|
console.log("Using enhanced database connection pooling with PG adapter");
|
|
// Dynamic import to defer URL parsing until runtime
|
|
const { createEnhancedPrismaClient } = require("./database-pool");
|
|
return createEnhancedPrismaClient();
|
|
}
|
|
|
|
// Default Prisma client with basic configuration
|
|
return new PrismaClient({
|
|
log:
|
|
process.env.NODE_ENV === "development"
|
|
? ["query", "error", "warn"]
|
|
: ["error"],
|
|
});
|
|
};
|
|
|
|
// Lazy initialization - only create when first accessed
|
|
let _prisma: PrismaClient | undefined;
|
|
|
|
const getPrisma = (): PrismaClient => {
|
|
if (!_prisma) {
|
|
_prisma = global.prisma || createPrismaClient();
|
|
// Save in global if we're in development to prevent multiple instances
|
|
if (process.env.NODE_ENV !== "production") {
|
|
global.prisma = _prisma;
|
|
}
|
|
}
|
|
return _prisma!;
|
|
};
|
|
|
|
// Export a proxy that lazily initializes the client
|
|
export const prisma = new Proxy({} as PrismaClient, {
|
|
get(_target, prop) {
|
|
return getPrisma()[prop as keyof PrismaClient];
|
|
},
|
|
});
|
|
|
|
// Graceful shutdown handling
|
|
const gracefulShutdown = async () => {
|
|
console.log("Gracefully disconnecting from database...");
|
|
await prisma.$disconnect();
|
|
process.exit(0);
|
|
};
|
|
|
|
// Handle process termination signals
|
|
process.on("SIGINT", gracefulShutdown);
|
|
process.on("SIGTERM", gracefulShutdown);
|
|
|
|
// Connection health check
|
|
export const checkDatabaseConnection = async (): Promise<boolean> => {
|
|
try {
|
|
await prisma.$queryRaw`SELECT 1`;
|
|
return true;
|
|
} catch (error) {
|
|
console.error("Database connection failed:", error);
|
|
return false;
|
|
}
|
|
};
|