refactor: Implement lazy initialization for Prisma client
- Introduced a lazy initialization function for the Prisma client to optimize resource usage by only initializing when first accessed. - Enhanced error handling for parsing Prisma Postgres connection strings, providing clearer error messages and logging for debugging. - Updated the export to use a Proxy for lazy loading, improving performance and maintaining the existing interface.
This commit is contained in:
parent
b25e1cab2d
commit
b060459f60
@ -6,6 +6,12 @@ const globalForPrisma = globalThis as unknown as {
|
||||
prisma: PrismaClient | undefined
|
||||
}
|
||||
|
||||
// Lazy initialization function - only initializes when prisma is first accessed
|
||||
function getPrismaClient(): PrismaClient {
|
||||
if (globalForPrisma.prisma) {
|
||||
return globalForPrisma.prisma
|
||||
}
|
||||
|
||||
const connectionString = process.env.DATABASE_URL
|
||||
|
||||
if (!connectionString) {
|
||||
@ -41,6 +47,20 @@ if (connectionString.startsWith('prisma+postgres://')) {
|
||||
}
|
||||
|
||||
const adapter = new PrismaPg(pool)
|
||||
export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter })
|
||||
const prisma = new PrismaClient({ adapter })
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
globalForPrisma.prisma = prisma
|
||||
}
|
||||
|
||||
return prisma
|
||||
}
|
||||
|
||||
// Export a proxy that lazily initializes Prisma on first access
|
||||
export const prisma = new Proxy({} as PrismaClient, {
|
||||
get(_target, prop) {
|
||||
const client = getPrismaClient()
|
||||
const value = (client as any)[prop]
|
||||
return typeof value === 'function' ? value.bind(client) : value
|
||||
}
|
||||
})
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user