From 1789e0460be5bfba6c86f168cecc14aaf49a5001 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 20 Apr 2026 07:53:55 +0000 Subject: [PATCH] fix: lazy DB init to prevent ECONNREFUSED on Vercel when DATABASE_URL is not set Agent-Logs-Url: https://github.com/WilliamK7/notionic/sessions/fe1cb4ab-a25d-440d-8a4e-ca9e1dc9231f Co-authored-by: WilliamK7 <82304956+WilliamK7@users.noreply.github.com> --- app/api/comments/[[...comment]]/route.js | 8 ++++++++ lib/comment-config.js | 2 -- lib/db.js | 7 +++++-- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/app/api/comments/[[...comment]]/route.js b/app/api/comments/[[...comment]]/route.js index 3ab03d60..c0fad3fe 100644 --- a/app/api/comments/[[...comment]]/route.js +++ b/app/api/comments/[[...comment]]/route.js @@ -1,9 +1,17 @@ +import { NextResponse } from 'next/server' import { NextComment } from '@fuma-comment/server/next' import { auth, storage } from '@/lib/comment-config' +import { ensureDbTables } from '@/lib/db' const { GET: _GET, POST: _POST, PATCH: _PATCH, DELETE: _DELETE } = NextComment({ auth, storage }) async function withParams(handler, req, ctx) { + try { + await ensureDbTables() + } catch (e) { + console.error('[comments] DB init failed:', e.message) + return NextResponse.json({ error: 'Database unavailable' }, { status: 503 }) + } const params = await ctx.params const normalized = { comment: params?.comment ?? [] } return handler(req, { ...ctx, params: Promise.resolve(normalized) }) diff --git a/lib/comment-config.js b/lib/comment-config.js index 450972a3..4c695869 100644 --- a/lib/comment-config.js +++ b/lib/comment-config.js @@ -5,8 +5,6 @@ import { authOptions } from './auth-options.js' import { db, ensureDbTables } from './db.js' import { comments, rates, roles, fumaUsers } from './comment-schema.js' -await ensureDbTables() - const nextAuthAdapter = createNextAuthAdapter(authOptions, { sessionId: 'id' }) export const auth = { diff --git a/lib/db.js b/lib/db.js index 761b7d47..fdc85c44 100644 --- a/lib/db.js +++ b/lib/db.js @@ -2,11 +2,14 @@ import { drizzle } from 'drizzle-orm/postgres-js' import postgres from 'postgres' import * as schema from './comment-schema.js' -const sql = postgres(process.env.DATABASE_URL, { onnotice: () => {} }) -export const db = drizzle(sql, { schema }) +const sql = process.env.DATABASE_URL + ? postgres(process.env.DATABASE_URL, { onnotice: () => {} }) + : null +export const db = sql ? drizzle(sql, { schema }) : null let initialized = false export async function ensureDbTables() { + if (!sql) return if (initialized) return initialized = true await sql`