2.4 KiB
auth-http.ts — fetch + navigate seam helpers
Purpose
auth-http.ts houses the three helpers every AuthProvider verb shares:
resolveFetch, resolveNavigate, and postJson. Each helper exists so the
AuthProvider body stays under the 300-LOC budget while keeping the
network-translation policy in a single, testable file. Failures from the
configured fetch are translated to REACT_AUTH_WL.AUTH_NETWORK_FAILED;
non-ok responses are translated to REACT_AUTH_WL.AUTH_REJECTED with the
backend-supplied message field threaded through the i18n message key when
present.
Features
resolveFetch(config)— pick the injectedfetchoverglobalThis.fetch.resolveNavigate(config)— pick the injectednavigate(url)over the defaultwindow.location.hrefwriter.postJson(fetchImpl, url, body, rejectMessage, options?)— single helper for every JSON POST, with error translation, optional credentials, and best-effort.json()recovery on failure responses.
Usage: Basic
const fetchImpl = resolveFetch(config);
const navigate = resolveNavigate(config);
const data = await postJson(fetchImpl, url, body, "ui.label.fallback_msg");
Usage: Advanced
try {
await postJson(fetchImpl, `${config.authUrl}/login`, { email, password },
"ui.login.rejected", { credentials: "include" });
} catch (err) {
if (err.code === REACT_AUTH_WL_CODES.AUTH_NETWORK_FAILED) {
showOfflineBanner();
} else if (err.code === REACT_AUTH_WL_CODES.AUTH_REJECTED) {
focusErrorRegion();
}
throw err;
}
API Reference
resolveFetch(config: AuthConfig): FetchLike— never throws; falls back toglobalThis.fetchwhen the config omits one.defaultNavigate(url: string): void— no-op whenwindowis undefined.resolveNavigate(config: AuthConfig): (url: string) => void— picks the injected seam or the default.postJson(fetchImpl, url, body, rejectMessage, options?)— returns the parsed JSON body. Errors are subclasses ofReactAuthWhitelabelError.
Implementation Notes
postJson swallows .json() parse errors on failure responses on purpose:
some backends return an empty 401/403 body, in which case the rejectMessage
fallback is the user-visible label. The .json() parse on success is also
swallowed and returns {} so a 204-style "no content" response keeps a
clean caller signature.