UNPKG

@karmaniverous/cached-axios

Version:

Tag‑aware caching for Axios: stable cache IDs, simple tag invalidation, and a drop‑in Orval mutator on top of axios‑cache‑interceptor.

48 lines (44 loc) 1.79 kB
import axios from 'axios'; import { setupCache } from 'axios-cache-interceptor'; /** * Shared Axios instance wrapped with axios-cache-interceptor (ACI). * * Defaults * - `interpretHeader: true` — honor HTTP cache headers. * - `staleIfError: true` — serve cached responses when revalidation fails. * - `ttl: 5 minutes` — fallback TTL if headers do not specify caching. * * Notes * - No `baseURL` is set; pass per-request baseURL/headers to keep helpers * safe for parallel calls across multiple backends. */ const base = axios.create(); /** Cache-aware Axios instance used by helpers and the Orval mutator. */ const cachedAxios = setupCache(base, { interpretHeader: true, staleIfError: true, ttl: 1000 * 60 * 5, // 5 minutes default if headers are missing }); /** * Orval-compatible mutator that executes through the shared cache-aware instance. * * Characteristics * - Always returns `AxiosResponse<T>` regardless of how the generator * instantiates the generic parameter. * - Calls through the `AxiosInstance` surface to avoid type mismatch with * ACI's `CacheRequestConfig` generic parameters. * - Shallow-merges `options` over `config` (options win). * * @typeParam T The expected response data type. * @typeParam R The request body type (if any). * @param config Base Axios request config from generated code. * @param options Optional overrides to merge over `config`. * @returns A promise resolving to `AxiosResponse<T>`. */ const orvalMutator = async (config, options) => { const final = { ...config, ...(options ?? {}) }; // Call through the base AxiosInstance signature to avoid CacheRequestConfig mismatch const res = await cachedAxios.request(final); return res; }; export { cachedAxios as c, orvalMutator as o };