All files / utils altchaVerifyFetch.ts

92.85% Statements 13/14
83.33% Branches 5/6
100% Functions 3/3
92.3% Lines 12/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44                    6x           6x 3x 3x   1x       4x 2x 2x       2x 2x 2x   2x                  
export type CaptchaVerifyResponse = {
  meta?: { success?: boolean };
  data?: { valid?: boolean };
  token?: string;
};
 
export function isCaptchaVerifySuccess(
  meta?: { success?: boolean },
  data?: { valid?: boolean }
): boolean {
  return meta?.success === true && data?.valid === true;
}
 
export function extractPayload(
  body: BodyInit | null | undefined
): string | undefined {
  if (typeof body !== "string") return undefined;
  try {
    return (JSON.parse(body) as { payload?: string }).payload;
  } catch {
    return undefined;
  }
}
 
export const captchaVerifyFetch: typeof fetch = async (url, init) => {
  const response = await fetch(url, init);
  Iif (!response.headers.get("content-type")?.includes("json")) {
    return response;
  }
 
  const json = (await response.json()) as CaptchaVerifyResponse;
  const payload = extractPayload(init?.body);
  const valid = isCaptchaVerifySuccess(json.meta, json.data);
 
  return Response.json(
    {
      ...json,
      verified: valid,
      payload,
    },
    { status: response.status }
  );
};