import { NextRequest, NextResponse } from 'next/server'; import { ZodSchema } from 'zod'; import { isApiError, ValidationError } from '@/lib/errors/api-errors'; type ApiHandler = ( request: NextRequest, validatedData: T ) => Promise; interface ApiHandlerOptions { validationSchema?: ZodSchema; skipValidation?: boolean; } export function withApiHandler( handler: ApiHandler, options: ApiHandlerOptions = {} ): (request: NextRequest) => Promise { return async (request: NextRequest) => { try { let validatedData: T; if (options.skipValidation) { validatedData = {} as T; } else if (options.validationSchema) { const body = await request.json(); const result = options.validationSchema.safeParse(body); if (!result.success) { throw new ValidationError('Invalid request data', result.error.errors); } validatedData = result.data as T; } else { validatedData = await request.json(); } return await handler(request, validatedData); } catch (error) { console.error('API Error:', error); if (isApiError(error)) { return NextResponse.json( { error: error.message, code: error.code, ...(error instanceof ValidationError && { details: error.details }) }, { status: error.statusCode } ); } // Unexpected error return NextResponse.json( { error: 'Internal server error' }, { status: 500 } ); } }; } /** * Simplified API handler for manual validation scenarios */ export async function apiHandler( handler: () => Promise ): Promise { try { const result = await handler(); return NextResponse.json(result); } catch (error) { console.error('API Error:', error); if (isApiError(error)) { return NextResponse.json( { error: error.message, code: error.code, ...(error instanceof ValidationError && { details: error.details }) }, { status: error.statusCode } ); } // Unexpected error return NextResponse.json( { error: 'Internal server error' }, { status: 500 } ); } }