diff --git a/src/lib/api-response.ts b/src/lib/api-response.ts index 797d420b4..940e4ca64 100644 --- a/src/lib/api-response.ts +++ b/src/lib/api-response.ts @@ -44,23 +44,29 @@ export function sanitiseZodIssues( })); } -export function returnAllZodIssues( - error: ZodError, - status: number = 422, - meta?: { - errorCode?: string; - headers?: Record; - } & Record, +type ErrorMeta = { + errorCode?: string; + headers?: Record; +} & Record; + +/** + * Shared builder for every `{ data: null, error, ... }` JSON envelope. + * Strips `headers` from the meta passthrough (it lands on the + * NextResponse constructor, not in the JSON body) and omits the `meta` + * key entirely when no non-header fields remain — so the unchanged + * `{ data: null, error: }` envelope still serialises byte- + * identically when the caller passes no extras. + */ +function buildJsonErrorResponse( + body: Record, + status: number, + meta: ErrorMeta | undefined, ): NextResponse { const { headers, ...rest } = meta ?? {}; const metaKeys = Object.keys(rest); return NextResponse.json( { - data: null, - error: "Validation failed", - details: { - issues: sanitiseZodIssues(error.issues), - }, + ...body, ...(metaKeys.length > 0 ? { meta: rest } : {}), }, { @@ -70,6 +76,22 @@ export function returnAllZodIssues( ); } +export function returnAllZodIssues( + error: ZodError, + status: number = 422, + meta?: ErrorMeta, +): NextResponse { + return buildJsonErrorResponse( + { + data: null, + error: "Validation failed", + details: { issues: sanitiseZodIssues(error.issues) }, + }, + status, + meta, + ); +} + /** * `meta` is additive — clients that ignore it see the unchanged * `{ data: null, error: }` envelope. New callers can pass @@ -86,24 +108,9 @@ export function returnAllZodIssues( export function apiError( message: string, status = 400, - meta?: { - errorCode?: string; - headers?: Record; - } & Record, + meta?: ErrorMeta, ) { - const { headers, ...rest } = meta ?? {}; - const metaKeys = Object.keys(rest); - return NextResponse.json( - { - data: null, - error: message, - ...(metaKeys.length > 0 ? { meta: rest } : {}), - }, - { - status, - ...(headers ? { headers } : {}), - }, - ); + return buildJsonErrorResponse({ data: null, error: message }, status, meta); } /**