|
| 1 | +/** |
| 2 | + * Admin API Response Helpers |
| 3 | + * |
| 4 | + * Consistent response formatting for all Admin API endpoints. |
| 5 | + */ |
| 6 | + |
| 7 | +import { NextResponse } from 'next/server' |
| 8 | +import type { |
| 9 | + AdminErrorResponse, |
| 10 | + AdminListResponse, |
| 11 | + AdminSingleResponse, |
| 12 | + PaginationMeta, |
| 13 | +} from '@/app/api/v1/admin/types' |
| 14 | + |
| 15 | +/** |
| 16 | + * Create a successful list response with pagination |
| 17 | + */ |
| 18 | +export function listResponse<T>( |
| 19 | + data: T[], |
| 20 | + pagination: PaginationMeta |
| 21 | +): NextResponse<AdminListResponse<T>> { |
| 22 | + return NextResponse.json({ data, pagination }) |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + * Create a successful single resource response |
| 27 | + */ |
| 28 | +export function singleResponse<T>(data: T): NextResponse<AdminSingleResponse<T>> { |
| 29 | + return NextResponse.json({ data }) |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Create an error response |
| 34 | + */ |
| 35 | +export function errorResponse( |
| 36 | + code: string, |
| 37 | + message: string, |
| 38 | + status: number, |
| 39 | + details?: unknown |
| 40 | +): NextResponse<AdminErrorResponse> { |
| 41 | + const body: AdminErrorResponse = { |
| 42 | + error: { code, message }, |
| 43 | + } |
| 44 | + |
| 45 | + if (details !== undefined) { |
| 46 | + body.error.details = details |
| 47 | + } |
| 48 | + |
| 49 | + return NextResponse.json(body, { status }) |
| 50 | +} |
| 51 | + |
| 52 | +// ============================================================================= |
| 53 | +// Common Error Responses |
| 54 | +// ============================================================================= |
| 55 | + |
| 56 | +export function unauthorizedResponse(message = 'Authentication required'): NextResponse { |
| 57 | + return errorResponse('UNAUTHORIZED', message, 401) |
| 58 | +} |
| 59 | + |
| 60 | +export function forbiddenResponse(message = 'Access denied'): NextResponse { |
| 61 | + return errorResponse('FORBIDDEN', message, 403) |
| 62 | +} |
| 63 | + |
| 64 | +export function notFoundResponse(resource: string): NextResponse { |
| 65 | + return errorResponse('NOT_FOUND', `${resource} not found`, 404) |
| 66 | +} |
| 67 | + |
| 68 | +export function badRequestResponse(message: string, details?: unknown): NextResponse { |
| 69 | + return errorResponse('BAD_REQUEST', message, 400, details) |
| 70 | +} |
| 71 | + |
| 72 | +export function internalErrorResponse(message = 'Internal server error'): NextResponse { |
| 73 | + return errorResponse('INTERNAL_ERROR', message, 500) |
| 74 | +} |
| 75 | + |
| 76 | +export function notConfiguredResponse(): NextResponse { |
| 77 | + return errorResponse( |
| 78 | + 'NOT_CONFIGURED', |
| 79 | + 'Admin API is not configured. Set ADMIN_API_KEY environment variable.', |
| 80 | + 503 |
| 81 | + ) |
| 82 | +} |
0 commit comments