0.1.6Updated a month ago
export type BodyValidationVerifyFunction = (verify_result?: boolean) => { fail: BodyValidationFailFunction }
type BodyValidationFailFunction = (error_text: string) => void
type CheckerFn<T> = (check: BodyValidationVerifyFunction, input: T) => void | void[];

const Verify: (errors: string[]) => BodyValidationVerifyFunction = (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 };
}