import type { NextFunction, Request, RequestHandler, Response } from 'express'; export function asyncHandler( handler: ( request: Request, response: Response, next: NextFunction, ) => Promise | unknown, ): RequestHandler { return (request, response, next) => { Promise.resolve(handler(request, response, next)).catch(next); }; } export function extractApiErrorMessage( rawText: string, fallbackMessage: string, ) { if (!rawText.trim()) { return fallbackMessage; } try { const parsed = JSON.parse(rawText) as { error?: { message?: string }; message?: string; code?: string; }; if (typeof parsed.error?.message === 'string' && parsed.error.message.trim()) { return parsed.error.message.trim(); } if (typeof parsed.message === 'string' && parsed.message.trim()) { return parsed.message.trim(); } if (typeof parsed.code === 'string' && parsed.code.trim()) { return `${fallbackMessage}(${parsed.code.trim()})`; } } catch { // Ignore malformed json responses. } return rawText.trim() || fallbackMessage; } export function jsonClone(value: T): T { return JSON.parse(JSON.stringify(value)) as T; }