Initial web
This commit is contained in:
26
web/lib/apiHelpers.ts
Normal file
26
web/lib/apiHelpers.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { isAuthorized, unauthorized } from './auth';
|
||||
|
||||
type RouteContext = { params: Promise<Record<string, string>> };
|
||||
type Handler = (req: NextRequest, ctx: RouteContext) => Promise<NextResponse>;
|
||||
|
||||
/**
|
||||
* Wraps a route handler with auth checking and unified error handling.
|
||||
*
|
||||
* @example
|
||||
* export const GET = withAuth(async (req) => {
|
||||
* const rows = await pool.query('...');
|
||||
* return NextResponse.json(rows);
|
||||
* });
|
||||
*/
|
||||
export function withAuth(handler: Handler): Handler {
|
||||
return async (req, ctx) => {
|
||||
if (!isAuthorized(req)) return unauthorized();
|
||||
try {
|
||||
return await handler(req, ctx);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user