liljudd-website/src/lib/responses.ts

39 lines
957 B
TypeScript

import httpStatus from "http-status";
import {
APIResponse,
Methods,
MyPaths,
ResponseSchemas,
StatusCodes,
} from "~/types/backend";
export function ErrorResponse<
P extends MyPaths,
M extends Methods<P>,
C extends StatusCodes<P, M> = StatusCodes<P, M>,
>(code: C, error?: string): APIResponse<P, M> {
console.log(code, error);
const responseData = {
error: error ?? httpStatus[`${httpStatus[code]}_NAME`],
};
return new Response(JSON.stringify(responseData), {
status: httpStatus[code],
headers: {
"Content-Type": "application/json",
},
});
}
export function Res<
P extends MyPaths,
M extends Methods<P>,
C extends StatusCodes<P, M> = StatusCodes<P, M>,
>(code: C, payload: ResponseSchemas<P, M, C>): APIResponse<P, M> {
return new Response(payload === null ? null : JSON.stringify(payload), {
status: httpStatus[code],
headers: {
"Content-Type": "application/json",
},
});
}