| import { ensureDb } from '@/lib/db' |
| import { NextRequest, NextResponse } from 'next/server' |
|
|
| type ApiHandler = (req: NextRequest, ctx?: { params: Promise<Record<string, string>> }) => Promise<NextResponse> |
|
|
| const SECURITY_HEADERS = { |
| 'X-Content-Type-Options': 'nosniff', |
| 'X-Frame-Options': 'DENY', |
| } |
|
|
| function applySecurityHeaders(response: NextResponse): NextResponse { |
| for (const [key, value] of Object.entries(SECURITY_HEADERS)) { |
| response.headers.set(key, value) |
| } |
| return response |
| } |
|
|
| |
| |
| |
| |
| |
| export function withDb(handler: ApiHandler): ApiHandler { |
| return async (req, ctx) => { |
| try { |
| await ensureDb() |
| } catch (error) { |
| console.error('[DB_INIT_ERROR]', error) |
| const errResponse = NextResponse.json( |
| { error: 'Database initialization failed. Please try again in a moment.' }, |
| { status: 503 } |
| ) |
| return applySecurityHeaders(errResponse) |
| } |
| const response = await handler(req, ctx) |
| return applySecurityHeaders(response) |
| } |
| } |