import { Pool } from 'pg' import { useRuntimeConfig } from '#imports' let _pool: Pool | null = null /** * 获取 PostgreSQL 连接池(懒加载单例) */ export function useDb(): Pool { if (_pool) { return _pool } const config = useRuntimeConfig() const connectionString = config.databaseUrl as string if (!connectionString) { throw createError({ statusCode: 500, statusMessage: 'DATABASE_URL 未配置,请设置 NUXT_DATABASE_URL 环境变量', }) } _pool = new Pool({ connectionString, max: 10 }) // 连接失败时输出可读错误,避免静默挂起 _pool.on('error', (err) => { console.error('[db] PostgreSQL 连接池错误:', err.message) }) return _pool }