Files
skills/docs/persistence/storage/storage-http/src/fetch-adapter/fetch-adapter.md
2026-05-29 08:20:56 +01:00

2.9 KiB

fetch-adapter

(no submodules)

Purpose

Wraps globalThis.fetch with the contract HttpStorage actually consumes. Translates raw network rejections (DNS failure, TLS error, connection reset, abort-without-signal) into a structured StorageHttpError carrying code STORAGE_HTTP.NETWORK_ERROR and the offending URL. AbortError is re-raised unchanged so the per-method wrapper in HttpStorage can map signal-driven cancellation to STORAGE_HTTP.ABORTED.

Features

  • Single function defaultFetch() returns a FetchLike bound to the global fetch.
  • NETWORK_ERROR mapping covers every kind of fetch reject that isn't an abort.
  • URL is extracted from string, URL, or Request inputs and attached to the error for diagnostics.
  • isAbortError(err) exposed for callers that need to distinguish abort from other failures without re-implementing the DOMException-shaped check.

Usage: Basic

import { defaultFetch } from "@suaveplan/storage-http";

const fetch = defaultFetch();
const response = await fetch("https://cdn.example.com/file.bin");

Usage: Advanced

import { defaultFetch, isAbortError, StorageHttpError, STORAGE_HTTP_CODES } from "@suaveplan/storage-http";

const fetch = defaultFetch();
try {
    const response = await fetch("https://cdn.example.com/file.bin", { signal });
    if (!response.ok) handleStatus(response.status);
} catch (err) {
    if (isAbortError(err)) return; // caller-driven cancellation
    if (err instanceof StorageHttpError && err.code === STORAGE_HTTP_CODES.NETWORK_ERROR) {
        operatorLog.error({ url: err.url, cause: err.cause }, "Origin unreachable");
    }
    throw err;
}

API Reference

defaultFetch(): FetchLike

Returns a FetchLike ((input, init?) => Promise<Response>) that:

  • Forwards to globalThis.fetch unchanged on success.
  • Re-raises AbortError unchanged for the caller's wrapper.
  • Maps every other fetch reject to StorageHttpError(STORAGE_HTTP.NETWORK_ERROR) with the resolved URL and the original error as cause.

isAbortError(err: unknown): boolean

Returns true when err is a non-null object with name === "AbortError". Runtime-neutral — works for both DOMException (browsers, Workers) and Node 18+'s native AbortError.

Implementation Notes

  • The adapter is intentionally thin. Status-code mapping (404 → undefined, 401 → UNAUTHORIZED, etc.) belongs to HttpStorage's per-method wrappers, not here, so this module stays usable for callers that want raw status access (e.g. a custom listing implementation).
  • URL extraction handles all three documented fetch input shapes. A pathological input that is none of them returns undefined URL on the error — the message still names the failure type.
  • globalThis.fetch is required (Node 18+, Bun, Deno, modern browsers, Workers). The package does not ship a polyfill — that would violate tier purity.