Files
Genarrative/server-node/src/http.ts
2026-04-08 16:41:29 +08:00

49 lines
1.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { NextFunction, Request, RequestHandler, Response } from 'express';
export function asyncHandler(
handler: (
request: Request,
response: Response,
next: NextFunction,
) => Promise<unknown> | 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<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T;
}