2.9 KiB
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 aFetchLikebound to the globalfetch. NETWORK_ERRORmapping covers every kind offetchreject that isn't an abort.- URL is extracted from
string,URL, orRequestinputs and attached to the error for diagnostics. isAbortError(err)exposed for callers that need to distinguish abort from other failures without re-implementing theDOMException-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.fetchunchanged on success. - Re-raises
AbortErrorunchanged for the caller's wrapper. - Maps every other
fetchreject toStorageHttpError(STORAGE_HTTP.NETWORK_ERROR)with the resolved URL and the original error ascause.
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 toHttpStorage'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
fetchinput shapes. A pathological input that is none of them returnsundefinedURL on the error — the message still names the failure type. globalThis.fetchis required (Node 18+, Bun, Deno, modern browsers, Workers). The package does not ship a polyfill — that would violate tier purity.