61 lines
1.3 KiB
TypeScript
61 lines
1.3 KiB
TypeScript
const statusMessages: Record<number, string> = {
|
|
200: "OK",
|
|
201: "Created",
|
|
204: "No Content",
|
|
400: "Bad Request",
|
|
401: "Unauthorized",
|
|
403: "Forbidden",
|
|
404: "Not Found",
|
|
500: "Internal Server Error",
|
|
};
|
|
|
|
function jsonResponse(
|
|
statusCode: number,
|
|
options: GenericJsonResponseOptions = {},
|
|
): Response {
|
|
const { headers, message, error, ...extra } = options;
|
|
|
|
if (statusCode === 204) {
|
|
return new Response(null, {
|
|
status: statusCode,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
...headers,
|
|
},
|
|
});
|
|
}
|
|
|
|
const statusMessage = statusMessages[statusCode] || "Unknown Status";
|
|
const jsonResponse: Record<string, unknown> = {};
|
|
|
|
if (statusCode >= 200 && statusCode < 300) {
|
|
jsonResponse.status = statusMessage;
|
|
if (message) jsonResponse.message = message;
|
|
} else {
|
|
jsonResponse.error = error || statusMessage;
|
|
if (message) jsonResponse.message = message;
|
|
}
|
|
|
|
const orderedResponse: Record<string, unknown> = {};
|
|
|
|
if ("status" in jsonResponse) {
|
|
orderedResponse.status = jsonResponse.status;
|
|
}
|
|
if ("error" in jsonResponse) {
|
|
orderedResponse.error = jsonResponse.error;
|
|
}
|
|
if ("message" in jsonResponse) {
|
|
orderedResponse.message = jsonResponse.message;
|
|
}
|
|
|
|
Object.assign(orderedResponse, extra);
|
|
|
|
return Response.json(orderedResponse, {
|
|
status: statusCode,
|
|
headers: {
|
|
...headers,
|
|
},
|
|
});
|
|
}
|
|
|
|
export { jsonResponse };
|