File size: 1,186 Bytes
eaab0a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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)
  }
}