guardedFetch

tcmts.atproto.guardedFetch · #nlmyhwna · term · runs anywhere

fetch, for a URL someone else gave (publicUrl checks it): redirects aren't followed (a server can't send tcm on to an address it wouldn't ask), and it gives up after ms (default 15 s).

import { publicUrl, Refused } from "#codebase/tcmts/atproto";

export async function guardedFetch(
  url: string,
  what: string,
  init: RequestInit = {},
  ms = 15_000,
): Promise<Response> {
  const u = await publicUrl(url, what);
  const res = await fetch(u, {
    ...init,
    redirect: "manual",
    signal: init.signal ?? AbortSignal.timeout(ms),
  });
  if (res.status >= 300 && res.status < 400)
    throw new Refused(`${what} (${u.host}) answered with a redirect, which isn't followed`);
  return res;
}

uses

used by