0.1.3•Updated 6 months ago
type CheckFn = (verify_result: boolean) => { fail: ErrorFn }
type ErrorFn = (error_text: string) => void
type CheckerFn<T> = (check: CheckFn, input: T) => void | void[];
const Verify: (errors: string[]) => CheckFn = (errors) => (result) => {
return {
fail: text => result || errors.push(text)
}
}
const ErrorResponse = (errors: string[]) => Response.json({ errors }, { status: 400 });
export const HandleBody = async <T = Record<string, any>>(req: Request, checker?: CheckerFn<T>) => {
let body: T;
try {
body = await req.json();
} catch(_) {
const errors = ['invalid payload'];
return { body: null, errors, error_response: ErrorResponse(errors) };
}
const errors: string[] = [];
checker?.(Verify(errors), body);
if(errors.length) {
return { body: null, errors, error_response: ErrorResponse(errors) }
}
return { body, errors, error_response: null } as { body: T, errors: string[], error_response: null };
}