@indra211/exios 3.0.0 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -196,6 +196,10 @@ try {
196
196
  }
197
197
  ```
198
198
 
199
+ `isExiosError` narrows the error type. Pass your API's error body type to type `err.response.data`: `if (isExiosError<{ message: string }>(err)) err.response?.data.message`.
200
+
201
+ Every option accepts an explicit `undefined`, meaning "use the default". This also type-checks with TypeScript's `exactOptionalPropertyTypes`, so `retry: { retries: process.env.RETRIES ? Number(process.env.RETRIES) : undefined }` works.
202
+
199
203
  `meta.url` is `baseURL + url` without the serialized `params`. A query string you wrote into `url` yourself is kept.
200
204
 
201
205
  `error.toJSON()` (and so `JSON.stringify(error)`) is **log-safe**: the values of `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`, `X-Api-Key`, `X-Auth-Token`, `X-XSRF-Token` and `X-CSRF-Token`, `auth.password`, proxy credentials and the request body are replaced with `"[REDACTED]"`. The error object itself (`error.config`) is not modified.
@@ -211,11 +215,11 @@ off(); // unsubscribe one listener
211
215
  api.off("retry"); // or remove every listener of an event
212
216
  ```
213
217
 
214
- | Event | When | Payload (besides `requestId`, `correlationId`, `method`, `url`, `config`, `timestamp`) |
218
+ | Event | When | Payload (besides `requestId`, `correlationId`, `method`, `url`, `config`, `metadata`, `timestamp`) |
215
219
  | ----------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
216
220
  | `request` | Once per logical request, after request interceptors, before the breaker | none |
217
221
  | `retry` | Before each backoff sleep | `attempt` (the one that failed), `delayMs`, `error?`, `status?` |
218
- | `timeout` | Every time an attempt times out (it may then be retried) | `attempt`, `timeoutMs`, `error` |
222
+ | `timeout` | An attempt hit `timeout` (it may be retried), or `totalTimeout` ended the request | `kind` (`'attempt'` / `'total'`), `attempt`, `timeoutMs`, `error` |
219
223
  | `response` | Final success, before response interceptors | `response`, `status`, `attempts`, `durationMs`, `responseTimeMs` |
220
224
  | `error` | Final failure, cancellations excluded | `error`, `code?`, `status?`, `attempts`, `durationMs` |
221
225
  | `canceled` | The request was canceled (`signal` or `CancelToken`) | `error`, `attempts`, `durationMs` |
@@ -228,6 +232,100 @@ api.off("retry"); // or remove every listener of an event
228
232
  - Listeners belong to one instance. `create()` does not copy them, just as it does not copy interceptors.
229
233
  - A request rejected by a request interceptor never dispatches, so it emits no events.
230
234
  - `retry.onRetry` and `breaker.onStateChange` keep working as before, and run before the events.
235
+ - Events describe network requests: a cache hit or a deduplicated caller makes none, so it emits none.
236
+
237
+ ## Request management
238
+
239
+ All of these are **off by default**. Turning them on never changes retry or breaker behaviour.
240
+
241
+ ### Total timeout
242
+
243
+ `timeout` limits each attempt. `totalTimeout` limits the whole request: every attempt, retry and backoff sleep.
244
+
245
+ ```js
246
+ api.get("/report", { timeout: 2000, totalTimeout: 10000 });
247
+ // at most 10 s in total, however many retries are left
248
+ ```
249
+
250
+ When it fires, the request rejects with `code: 'ECONNABORTED'` (`'ETIMEDOUT'` with `transitional.clarifyTimeoutError`) and the message `total timeout of 10000ms exceeded`. The `timeout` event fires with `kind: 'total'`. Like a cancellation, it does **not** count as a circuit breaker failure. Your own `signal` / `CancelToken` still produce a `CanceledError`. For `responseType: 'stream'` the limit ends when the headers arrive.
251
+
252
+ ### Request metadata
253
+
254
+ `metadata` is free-form data that travels with a request. It is readable in interceptors, adapters and every event (`event.metadata`), and it is never sent to the server. Instance and request metadata are merged.
255
+
256
+ ```js
257
+ const api = exios.create({ metadata: { feature: "checkout" } });
258
+ api.on("error", (e) => report(e.metadata?.feature, e.code));
259
+ api.get("/cart", { metadata: { step: "load" } }); // metadata: { feature: "checkout", step: "load" }
260
+ ```
261
+
262
+ ### Request deduplication
263
+
264
+ With `dedupe: true`, identical requests made while one is already in flight share a single network request.
265
+
266
+ ```js
267
+ const api = exios.create({ baseURL: "https://api.example.com", dedupe: true });
268
+ const [a, b] = await Promise.all([api.get("/me"), api.get("/me")]); // one network request
269
+ b.meta.deduped; // true
270
+ ```
271
+
272
+ - **What counts as identical:** same method, URL, params, headers, `auth` and `responseType`, and the same request policy: `timeout`, `totalTimeout`, `validateStatus`, `transformResponse`, `responseEncoding`, `retry`, `breaker`, `adapter` and size limits. The shared request runs with one caller's settings, so callers with different settings never share it. Functions match by identity: the instance's shared defaults match; an inline arrow function written per call does not. Requests with different `Authorization` headers are never shared.
273
+ - **Methods:** only `GET` and `HEAD` are deduplicated, unless you list others in `dedupe: { methods: [...] }`. Requests with a body, and `responseType: 'stream'`, are never shared.
274
+ - **Cancellation:** each caller keeps its own `signal` / `CancelToken`. A caller that aborts is rejected at once, and the others still get the response. The network request is aborted only when **every** caller has aborted.
275
+ - **Separate results:** every caller gets its own response object, with its own `requestId` and a cloned copy of `data`, and runs its own response interceptors. Errors are passed to every caller. When `data` can't be copied exactly (class instances, functions), callers share the same object: treat it as read-only.
276
+ - **Custom key:** `dedupe: { key: (config) => string | undefined }`. Return `undefined` to skip deduplication for a request.
277
+ - **Events:** lifecycle events and request interceptors see the first caller's request. `onDownloadProgress` / `onUploadProgress` fire only for that caller.
278
+
279
+ ### Response caching
280
+
281
+ ```js
282
+ const api = exios.create({
283
+ baseURL: "https://api.example.com",
284
+ cache: { ttl: 30_000 }, // or cache: true (ttl 60 s)
285
+ });
286
+ await api.get("/products"); // network
287
+ const res = await api.get("/products"); // from memory
288
+ res.meta.cached; // true
289
+ ```
290
+
291
+ | Option | Default | Meaning |
292
+ | --------------------- | ---------------------------- | ----------------------------------------------------------------------------------------- |
293
+ | `ttl` | `60000` | Time to live in ms |
294
+ | `methods` | `['get', 'head']` | Methods whose responses may be cached |
295
+ | `respectCacheControl` | `true` | Honour `no-store`, `no-cache` and `max-age` on requests and responses |
296
+ | `key` | method + URL + params + headers hash | `(config) => string \| undefined`; `undefined` skips the cache for that request |
297
+ | `provider` | built-in memory LRU (100 entries) | Any object with `get` / `set` / `delete` / `clear` (sync or async), plus optional `keys` |
298
+
299
+ - **What is stored:** only 2xx responses. Errors, request bodies and streams are never cached. Neither is data that `structuredClone` can't copy exactly: class instances (for example from a custom `transformResponse`), functions, or Node `Buffer`s anywhere in the data. Plain objects, arrays, `Date`, `Map`, `Set`, `RegExp`, typed arrays, `ArrayBuffer` and `Blob` are fine.
300
+ - **Transforms:** the key includes `transformResponse` and `responseEncoding`, so differently transformed data is never mixed. An inline `transformResponse` written per call gets a new key each time, so it never hits the cache: define it once and reuse it.
301
+ - **Isolated data:** every response read from the cache gets its own copy of `data`, so changing it can't affect the cache or other callers.
302
+ - **Credentials:** the key includes a hash of the request headers and `auth`, so requests made with different credentials never share an entry. Secrets never appear in the key text.
303
+ - **Cache-Control:** a response with `no-store` or `no-cache` is not stored, and `max-age` shortens the `ttl`. A request sent with `Cache-Control: no-cache` skips the read and refreshes the entry; `no-store` skips both the read and the write.
304
+ - **Per request:** `cache: false` bypasses the cache; `cache: { ttl: 5000 }` overrides the ttl.
305
+ - **Failures:** a cache provider that throws never fails the request. The error is reported with `console.error`, and the request goes to the network.
306
+ - **Instances:** each instance (including each `create()` child) has its own memory cache, unless you pass a `provider`.
307
+
308
+ Managing the cache:
309
+
310
+ ```js
311
+ await api.cache.invalidate("/products"); // /products, /products?page=2, /products/42 (not /products-old)
312
+ await api.cache.invalidate(/\/users\//); // RegExp tested against keys
313
+ await api.cache.invalidate((key) => key.startsWith("GET")); // predicate; resolves with the number removed
314
+ await api.cache.delete(api.cache.key({ url: "/products" })); // one entry
315
+ await api.cache.clear();
316
+ ```
317
+
318
+ A custom provider, for example backed by `localStorage` or Redis:
319
+
320
+ ```js
321
+ import { MemoryCache } from "@indra211/exios";
322
+
323
+ const api = exios.create({ cache: { provider: new MemoryCache({ maxEntries: 500 }) } });
324
+ // or: { get(key), set(key, entry), delete(key), clear(), keys?() }; entries are plain objects
325
+ // { status, statusText, headers, data, storedAt, expiresAt }
326
+ ```
327
+
328
+ `invalidate()` needs a provider with `keys()`; without one it rejects with `ERR_NOT_SUPPORT`.
231
329
 
232
330
  ## Behavior rules
233
331