test8 / src /lib /api-handler.ts
simikkk's picture
Upload 93 files
eaab0a9 verified
Raw
History Blame Contribute Delete
1.19 kB
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
}
/**
* Wraps an API route handler with automatic DB initialization
* and security headers on all responses.
* Every API route should use this to ensure tables exist before querying.
*/
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)
}
}