okJson

tcmts.atproto.okJson · #xm5ij5z2 · term · runs anywhere

A JSON answer, or an error saying what the service said.

import { cappedBytes } from "#codebase/tcmts/atproto";

export async function okJson<T>(res: Response, what: string): Promise<T> {
  // (no JSON answer tcm reads is near this; one that is, is refused rather than read)
  const text = new TextDecoder().decode(await cappedBytes(res, 8 * 1024 * 1024, what));
  let body: { error?: string; message?: string; error_description?: string } | undefined;
  try {
    body = JSON.parse(text);
  } catch {
    body = undefined;
  }
  if (!res.ok) {
    const why =
      body?.error_description ??
      body?.message ??
      body?.error ??
      (text.slice(0, 200) || res.statusText);
    throw new Error(`${what}: ${res.status} ${why}`);
  }
  if (body === undefined) throw new Error(`${what}: not JSON`);
  return body as T;
}

uses

used by