UNPKG

everything-dev

Version:

A consolidated product package for building Module Federation apps with oRPC APIs.

95 lines (93 loc) • 3.57 kB
import { useRouter } from "@tanstack/react-router"; import { createORPCClient, onError } from "@orpc/client"; import { RPCLink } from "@orpc/client/fetch"; import { createTanstackQueryUtils } from "@orpc/tanstack-query"; //#region src/ui/api.ts const RATE_LIMIT_MAX_RETRIES = 3; const RATE_LIMIT_RETRY_CAP_MS = 2e3; const browserClients = /* @__PURE__ */ new Map(); async function fetchWithBrowserDefaults(fetchUrl, headers, options) { const init = { ...options, credentials: "include", headers: mergeHeaders(headers, options?.headers) }; let response = await fetch(fetchUrl, init); for (let attempt = 1; attempt <= RATE_LIMIT_MAX_RETRIES && response.status === 429; attempt++) { const retryAfterSeconds = Number(response.headers.get("retry-after")); const delay = Number.isFinite(retryAfterSeconds) && retryAfterSeconds > 0 ? Math.min(retryAfterSeconds * 1e3, RATE_LIMIT_RETRY_CAP_MS) : 100 * attempt; await new Promise((resolve) => setTimeout(resolve, delay)); response = await fetch(fetchUrl, init); } return response; } function mergeHeaders(base, overrides) { const merged = new Headers(base); new Headers(overrides).forEach((value, key) => { merged.set(key, value); }); return merged; } function buildBrowserClient(hostUrl, path, headers, connectionError) { return createORPCClient(new RPCLink({ origin: hostUrl, url: path, interceptors: [onError((error) => { if (typeof window === "undefined") return; if (!(error && typeof error === "object" && "message" in error)) return; const message = String(error.message).toLowerCase(); if (!message.includes("fetch") && !message.includes("network") && !message.includes("failed to fetch")) return; import("sonner").then(({ toast }) => { const copy = connectionError?.() ?? { title: "Unable to connect to API", description: "The API is currently unavailable. Please try again later." }; toast.error(copy.title, { id: "api-connection-error", description: copy.description }); }).catch(() => {}); })], fetch(fetchUrl, options) { return fetchWithBrowserDefaults(fetchUrl, headers, options); } })); } function clientFor(hostUrl, path, headers, connectionError) { if (typeof window !== "undefined" && !headers) { const key = `${hostUrl}${path}`; const memoized = browserClients.get(key); if (memoized) return memoized; const client = buildBrowserClient(hostUrl, path, headers, connectionError); browserClients.set(key, client); return client; } return buildBrowserClient(hostUrl, path, headers, connectionError); } function createApiClient(config, headers) { return clientFor(config.hostUrl, config.rpcBase, headers, config.connectionError); } function createPluginApiClient(pluginKey, config, headers) { return clientFor(config.hostUrl, `${config.rpcBase}/${pluginKey}`, headers, config.connectionError); } function createServiceClients(config, keys, headers) { const clients = {}; for (const key of keys) if (key === "api") clients[key] = createApiClient(config, headers); else clients[key] = createPluginApiClient(key, config, headers); return clients; } function useClientContext() { return useRouter().options.context; } function useApiClient() { return useClientContext().apiClient; } function useOrpc() { return createTanstackQueryUtils(useApiClient()); } function usePluginClients() { return useClientContext().pluginClients ?? {}; } //#endregion export { createApiClient, createPluginApiClient, createServiceClients, useApiClient, useOrpc, usePluginClients }; //# sourceMappingURL=api.mjs.map