fetch-layers 0.0.0-stage → 1.1.0
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/CHANGELOG.md +39 -0
- package/LICENSE +21 -0
- package/README.md +313 -2
- package/README.ru.md +314 -0
- package/dist/classify-body-DOG6Vbf_.mjs +2 -0
- package/dist/classify-body-DOG6Vbf_.mjs.map +1 -0
- package/dist/errors-BITxtr5V.d.mts +116 -0
- package/dist/index.d.mts +70 -0
- package/dist/index.mjs +2 -0
- package/dist/index.mjs.map +1 -0
- package/dist/layer-3tx7wJdK.d.mts +133 -0
- package/dist/layer-BvZMV3L4.d.mts +104 -0
- package/dist/layer-C5h5TXG6.d.mts +247 -0
- package/dist/layer-CH2X3ibX.d.mts +117 -0
- package/dist/layer-DQ0xiRMN.mjs +2 -0
- package/dist/layer-DQ0xiRMN.mjs.map +1 -0
- package/dist/layers/auth/index.d.mts +13 -0
- package/dist/layers/auth/index.mjs +1 -0
- package/dist/layers/idempotency/index.d.mts +16 -0
- package/dist/layers/idempotency/index.mjs +1 -0
- package/dist/layers/index.d.mts +62 -0
- package/dist/layers/index.mjs +2 -0
- package/dist/layers/index.mjs.map +1 -0
- package/dist/layers/retry/index.d.mts +2 -0
- package/dist/layers/retry/index.mjs +1 -0
- package/dist/reset-registry-CQPiZVBB.mjs +2 -0
- package/dist/reset-registry-CQPiZVBB.mjs.map +1 -0
- package/dist/session-CcBNIxp4.mjs +2 -0
- package/dist/session-CcBNIxp4.mjs.map +1 -0
- package/dist/shared/storage.d.mts +2 -0
- package/dist/shared/storage.mjs +2 -0
- package/dist/shared/storage.mjs.map +1 -0
- package/dist/signals-DQjF6ojU.mjs +2 -0
- package/dist/signals-DQjF6ojU.mjs.map +1 -0
- package/dist/storage-C0XsVkz-.d.mts +45 -0
- package/package.json +99 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 1.1.0
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- `StorageSourceOptions` (`maxEntries`, `storageKey`, `generateKey`) for `sessionStorageSource`, `localStorageSource` and `memoryStorageSource`.
|
|
8
|
+
- Source maps are shipped with the package.
|
|
9
|
+
- README: idempotency storage section — what is stored, how to pick a source, XSS/ITP, tabs, multi-tenant and SSR limits.
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- Requires Node.js >= 22.18.0.
|
|
14
|
+
- Idempotency records are stored under JSON tuple keys, so `|` inside scope, query or body no longer collides.
|
|
15
|
+
- The default idempotency scope includes the base URL, so the same path on different hosts does not share a key.
|
|
16
|
+
- `lastUsedAt` is written at most once per second per key to avoid synchronous `localStorage` writes on every request.
|
|
17
|
+
- Documented that `onBeforeRetry` does not run for 409 by default: add 409 to `shouldRetry` to handle it there.
|
|
18
|
+
|
|
19
|
+
### Fixed
|
|
20
|
+
|
|
21
|
+
- Idempotency: only the key that was sent is released on resolve; a concurrent request's key is no longer dropped.
|
|
22
|
+
- Idempotency: the last used key is kept on eviction; ties inside one millisecond are broken by a monotonic counter.
|
|
23
|
+
- Idempotency: a failed touch write no longer blocks the request.
|
|
24
|
+
- Idempotency: invalid keys and corrupted storage records are rejected.
|
|
25
|
+
- Auth: single-use bodies are not resent after a refresh.
|
|
26
|
+
- Auth: hardened refresh result handling.
|
|
27
|
+
- Transport: response metadata is kept when `parseErrorBody` throws.
|
|
28
|
+
- Retry: the unsafe-retry warning is skipped when `maxAttempts` is 1.
|
|
29
|
+
|
|
30
|
+
## 1.0.0
|
|
31
|
+
|
|
32
|
+
- Layer pipeline: idempotency -> retry -> auth.
|
|
33
|
+
- `withAuth`: single-flight refresh, circuit breaker, cooldown, `resetRefreshCircuit`.
|
|
34
|
+
- `withIdempotency`: one key per operation, `IdempotencySource`, sources for `sessionStorage`, `localStorage`, memory.
|
|
35
|
+
- `withRetry`: exponential backoff with jitter, `Retry-After` support.
|
|
36
|
+
- `ApiError` with structural fields, content fields from the response body, and getters.
|
|
37
|
+
- Error body: flat parser as default, `ErrorBodyParser` as extension point for custom formats.
|
|
38
|
+
- Transport: JSON, `FormData`, `Blob`, `File`, `ArrayBuffer`, `TypedArray`, `URLSearchParams`, `ReadableStream`, Node.js `Readable`.
|
|
39
|
+
- Cross-realm type detection, recursive rejection of non-serializable bodies.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 smlnkv
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,314 @@
|
|
|
1
|
-
#
|
|
1
|
+
# fetch-layers
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**English** | [Русский](./README.ru.md)
|
|
4
|
+
|
|
5
|
+
An HTTP client built from layers. Each layer handles a single concern: auth, retries, idempotency. Layers are added as needed, and the order is validated at client creation.
|
|
6
|
+
|
|
7
|
+
Three built-in layers:
|
|
8
|
+
|
|
9
|
+
- `withAuth` - token refresh on 401, one refresh for all concurrent requests
|
|
10
|
+
- `withRetry` - retries 5xx and network errors, honors `Retry-After`
|
|
11
|
+
- `withIdempotency` - one `Idempotency-Key` per operation, including retries
|
|
12
|
+
|
|
13
|
+
Errors from layers and transport come back as `ApiError`. Zero dependencies, tree-shaking.
|
|
14
|
+
|
|
15
|
+
## Contents
|
|
16
|
+
|
|
17
|
+
- [Who it's for](#who-its-for)
|
|
18
|
+
- [Problems it solves](#problems-it-solves)
|
|
19
|
+
- [Features](#features)
|
|
20
|
+
- [Install and first request](#install-and-first-request)
|
|
21
|
+
- [Idempotency storage](#idempotency-storage)
|
|
22
|
+
- [Requirements](#requirements)
|
|
23
|
+
- [Modules](#modules)
|
|
24
|
+
- [How layers work](#how-layers-work)
|
|
25
|
+
- [Working with TanStack Query](#working-with-tanstack-query)
|
|
26
|
+
|
|
27
|
+
## Who it's for
|
|
28
|
+
|
|
29
|
+
- **SPA with auth.** Several requests go out at once, all get 401. `withAuth` runs a single refresh for all of them and resends each request with the new token.
|
|
30
|
+
|
|
31
|
+
- **API with mutations.** Orders, payments, bookings. You need to retry 5xx and timeouts, but a retried POST /orders creates a second order. `withIdempotency` generates a key once and keeps it until the server confirms.
|
|
32
|
+
|
|
33
|
+
- **Several APIs in one app.** Public and private, different tokens, different error shapes. Each API gets its own client with its own layers and its own `SessionProvider`.
|
|
34
|
+
|
|
35
|
+
- **SSR and BFF.** Next.js route handlers, Remix loaders, Nuxt server routes. The same 401 and refresh flow as in a SPA, but without `localStorage` - use `memoryStorageSource`.
|
|
36
|
+
|
|
37
|
+
## Problems it solves
|
|
38
|
+
|
|
39
|
+
### Session expired, requests fail with 401
|
|
40
|
+
|
|
41
|
+
Five requests go out at once, all get 401. Without coordination each request starts its own refresh - five refresh calls instead of one. The token is written to storage five times in a race: the last one wins, but some requests keep the old token and get 401 again.
|
|
42
|
+
|
|
43
|
+
`withAuth` collects every waiting request into a single refresh. While it runs, the rest wait. Once the token is fresh, each request is sent again with the new header. One refresh instead of five.
|
|
44
|
+
|
|
45
|
+
### Retries and duplicates
|
|
46
|
+
|
|
47
|
+
Network errors and 5xx: server may be down, connection may drop. A retry often succeeds on the second or third attempt.
|
|
48
|
+
|
|
49
|
+
A retry creates duplicates when the operation is not idempotent. POST /orders on retry creates two orders: the first one may have reached the server, the response was lost, the retry created another.
|
|
50
|
+
|
|
51
|
+
The fix is `Idempotency-Key`. The server matches it against previous requests and returns the result of the first one. The catch: the key must stay the same across the whole logical operation, including all retries and any refresh in between.
|
|
52
|
+
|
|
53
|
+
`withIdempotency` generates the key once, before the first attempt, and keeps it until the server confirms. Even if the request failed on the network and replays five minutes later from somewhere else - same key.
|
|
54
|
+
|
|
55
|
+
The key outlives the request, so it needs storage. Which source to pick and what ends up in it: [Idempotency storage](#idempotency-storage).
|
|
56
|
+
|
|
57
|
+
### Different error shapes
|
|
58
|
+
|
|
59
|
+
Every backend has its own error format. One returns `{ code, message }`, another `{ error: { code } }`, a third RFC 7807. Without a common mechanism, the parsing has to be repeated everywhere an error is handled.
|
|
60
|
+
|
|
61
|
+
The library splits error fields into two layers. The structural layer is the same for every backend: `kind`, `status`, `isRetryable`, `isCancelled`, `isUncertain`, `requestId` (from the `X-Request-Id` header), `retryAfterMs`. The content layer comes from the response body: `code`, `message`, `fields`, `details`. By default the client understands the flat shape `{ code, message, fields }` and plain text. For other formats (Fastify, RFC 7807, DRF, Laravel, `{ error: { code } }`) the app passes its own parsing function via `parseErrorBody`.
|
|
62
|
+
|
|
63
|
+
The full response body is always available in `err.rawBody`, even when the format isn't recognized.
|
|
64
|
+
|
|
65
|
+
### Token refresh temporarily unavailable
|
|
66
|
+
|
|
67
|
+
Token refresh may fail: network is down, refresh endpoint returns 5xx. Without protection every new 401 starts another refresh attempt, and this adds load on the server.
|
|
68
|
+
|
|
69
|
+
`withAuth` blocks refresh for a while after a failure. While the block is active, 401s are returned to the app without an attempt to refresh. `onCircuitOpen` and `onCircuitClose` report when the breaker opens or closes.
|
|
70
|
+
|
|
71
|
+
## Features
|
|
72
|
+
|
|
73
|
+
- **Auth.** `withAuth` works with any `SessionProvider`. To wire the layer up, implement three methods: `getAuthHeaders`, `refresh`, `clear`. Three refresh states (`success`, `definitely-failed`, `temporarily-failed`) give the app control: log the user out or retry later. Circuit breaker settings: `circuitBreakerMs` and `refreshTimeoutMs`. The breaker opens only on network errors, timeouts and 5xx, not on errors in `refresh`. The `resetRefreshCircuit(client)` function resets it manually when the app knows the problem is gone.
|
|
74
|
+
|
|
75
|
+
- **Idempotency.** `withIdempotency` adds an `Idempotency-Key` header to every mutating method (POST, PUT, PATCH, DELETE). For endpoints that do not accept the header, pass `skipIdempotency: true` on the request. The key can live in `localStorage`, `sessionStorage` or memory - depending on whether you need it to survive a reload; see [Idempotency storage](#idempotency-storage) for what ends up in storage. The fingerprint includes `baseUrl`, path, query and body, so two APIs sharing one storage never share a key. For custom storage there is the `IdempotencySource` interface (two methods) and the `stableSerialize` helper. `maxEntries` limits the store size, eviction by last use time. `storageKey` keeps several APIs on one origin in separate records.
|
|
76
|
+
|
|
77
|
+
- **Retries.** `withRetry` is configurable: `maxAttempts`, `baseDelayMs`, `maxDelayMs`, `jitterRatio`, `retryOnNetwork`, `retryOnTimeout`. Custom policies via `shouldRetry`, `computeDelay`, `onBeforeRetry`. `Retry-After` from the server takes priority over the computed delay. By default only network errors, timeouts, 408, 429 and 5xx are retried: `onBeforeRetry` runs only for those, so handling 409 there requires adding it to `shouldRetry` first.
|
|
78
|
+
|
|
79
|
+
- **Errors.** `ApiError` with getters `isRetryable`, `isCancelled`, `isAuthError`, `isUncertain` and others. `err.fields` is a ready-to-use `Record<string, string>` for forms, when the server returns the flat shape. `err.rawBody` - the original response body for everything else. Custom parsing via `parseErrorBody`.
|
|
80
|
+
|
|
81
|
+
- **Transport.** Validates `baseUrl`, `timeoutMs`, `fetch` and layer order at client creation. Headers accept `Record`, `Headers` or an array of pairs. `defaultHeaders` for common headers. `timeoutMs` and `signal` in a specific request. `requestWithMeta` returns HTTP metadata together with data - for cases when a response header affects the next step: `Retry-After` in `202 Accepted`, `Location` in `201`, `X-Request-Id` for logs. `fetchOptions` for other `fetch` params.
|
|
82
|
+
|
|
83
|
+
For async operations the server may answer `202 Accepted` with a `Retry-After` header. The pause value in milliseconds is available in `meta.retryAfterMs` - exactly as the server sent it. The library does not cap the value: the app decides how long to wait.
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
const { meta } = await client.requestWithMeta({
|
|
87
|
+
path: '/api/jobs',
|
|
88
|
+
method: 'POST',
|
|
89
|
+
body: { action: 'start' },
|
|
90
|
+
});
|
|
91
|
+
await new Promise((resolve) => setTimeout(resolve, meta.retryAfterMs ?? 1000));
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
- **Request bodies.** JSON, `FormData`, `Blob`, `File`, `ArrayBuffer`, `TypedArray`, `DataView`, `URLSearchParams`, `ReadableStream`, Node.js `stream.Readable`. Works with types from iframes and Workers. Recursive check: nested non-serializable values are rejected before the request is sent with `BODY_SERIALIZATION_ERROR`.
|
|
95
|
+
|
|
96
|
+
- **Layers.** A custom layer is an object with four fields: `name`, `stage`, `wrap`, `attach`. `LayerContext` exposes `warn`. Priorities `2.5` and `1.5` for inserting between built-in layers.
|
|
97
|
+
|
|
98
|
+
## Install and first request
|
|
99
|
+
|
|
100
|
+
```
|
|
101
|
+
npm install fetch-layers
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import { createClient } from 'fetch-layers';
|
|
106
|
+
|
|
107
|
+
const client = createClient({ baseUrl: '/api' });
|
|
108
|
+
|
|
109
|
+
const products = await client.get<Product[]>('/products');
|
|
110
|
+
|
|
111
|
+
const review = await client.post('/reviews', {
|
|
112
|
+
productId: products[0].id,
|
|
113
|
+
rating: 5,
|
|
114
|
+
comment: 'Great product',
|
|
115
|
+
});
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Both methods return the parsed response body. `post` sends an object as JSON. Any error comes back as `ApiError` - catch it with `try/catch` or `.catch()`.
|
|
119
|
+
|
|
120
|
+
### Wiring up layers
|
|
121
|
+
|
|
122
|
+
The `layers` option takes an array of layers, ordered from outermost to innermost:
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
import { createClient } from 'fetch-layers';
|
|
126
|
+
import {
|
|
127
|
+
withAuth,
|
|
128
|
+
withRetry,
|
|
129
|
+
withIdempotency,
|
|
130
|
+
sessionStorageSource,
|
|
131
|
+
} from 'fetch-layers/layers';
|
|
132
|
+
|
|
133
|
+
const client = createClient({
|
|
134
|
+
baseUrl: '/api',
|
|
135
|
+
layers: [
|
|
136
|
+
withIdempotency(sessionStorageSource()),
|
|
137
|
+
withRetry({ maxAttempts: 3 }),
|
|
138
|
+
withAuth({ provider: sessionProvider }),
|
|
139
|
+
],
|
|
140
|
+
});
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
What the layers do, in this order:
|
|
144
|
+
|
|
145
|
+
- `withIdempotency` wraps everything else. The key is generated once per operation and stays put across retries.
|
|
146
|
+
- `withRetry` retries on 5xx, network errors and timeouts, without changing the key.
|
|
147
|
+
- `withAuth` adds auth headers and refreshes the token on 401.
|
|
148
|
+
|
|
149
|
+
The order is not arbitrary - the library validates it at client creation. Swap `withIdempotency` and `withRetry` and the key gets regenerated on every retry - that breaks deduplication. `createClient` throws with the name of the layer that breaks the rule.
|
|
150
|
+
|
|
151
|
+
If you don't need layers, `createClient({ baseUrl: '/api' })` gives you a plain HTTP client without auth, retries or idempotency.
|
|
152
|
+
|
|
153
|
+
### Refresh endpoint: a separate client
|
|
154
|
+
|
|
155
|
+
`provider.refresh` must not send the refresh request through a client that has `withAuth`. A 401 from the refresh endpoint comes back into `withAuth`, which calls `provider.refresh` again. If `refresh` passed its `signal` to the request, the layer recognizes its own refresh call, warns and rethrows 401; if not, the request and the refresh wait on each other. Use a separate client without the auth layer for the refresh endpoint:
|
|
156
|
+
|
|
157
|
+
```ts
|
|
158
|
+
const authClient = createClient({ baseUrl: '/auth' });
|
|
159
|
+
|
|
160
|
+
const sessionProvider: SessionProvider = {
|
|
161
|
+
getAuthHeaders: () => ({ Authorization: `Bearer ${tokens.access}` }),
|
|
162
|
+
refresh: async (signal) => {
|
|
163
|
+
const next = await authClient.post<Tokens>('/refresh', {
|
|
164
|
+
refreshToken: tokens.refresh,
|
|
165
|
+
}, { signal });
|
|
166
|
+
tokens = next;
|
|
167
|
+
return { status: 'success', headers: { Authorization: `Bearer ${next.access}` } };
|
|
168
|
+
},
|
|
169
|
+
clear: () => {
|
|
170
|
+
tokens = null;
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
The main client keeps `withAuth` and handles 401 on regular requests. The separate client is used only inside `provider.refresh`, so the refresh request carries no auth headers and is not retried.
|
|
176
|
+
|
|
177
|
+
## Idempotency storage
|
|
178
|
+
|
|
179
|
+
The key outlives the request, so it needs storage. The record is keyed by a fingerprint of the request and holds that fingerprint as plain text: the serialized body, query params and `baseUrl`. There is no TTL - a record is deleted only when the server confirms or explicitly rejects the operation. After an unknown outcome (network, timeout, 5xx) the record stays in storage until it is evicted by `maxEntries`.
|
|
180
|
+
|
|
181
|
+
| Source | Survives reload | What is written | Use for |
|
|
182
|
+
|---|---|---|---|
|
|
183
|
+
| `memoryStorageSource` | no | nothing | card data, credentials, personal data, SSR, payment widgets |
|
|
184
|
+
| `sessionStorageSource` | no, lives with the tab | body, query, baseUrl | regular app on its own origin |
|
|
185
|
+
| `localStorageSource` | yes | body, query, baseUrl | when a duplicate after F5 costs more than exposure |
|
|
186
|
+
|
|
187
|
+
Where the record physically lives depends on the source. `localStorageSource` persists it in the browser profile, so it survives a reload and a browser restart. `sessionStorageSource` keeps it in the tab: it is gone when the tab closes, and whether the browser restores it after a crash or session restore is up to the browser. `memoryStorageSource` keeps it in the process heap and loses it with the process. With your own `StorageLike` the library only knows what that adapter does.
|
|
188
|
+
|
|
189
|
+
`localStorage` and `sessionStorage` are readable by any script on the origin: an XSS, a browser extension, analytics, tag managers, embedded widgets. For card numbers, CVVs, IBANs, tokens or personal data use `memoryStorageSource` and let the server deduplicate. A lost key means a possible duplicate; a leaked body cannot be undone.
|
|
190
|
+
|
|
191
|
+
Safari ITP clears script-writable storage after seven days without a visit, so `localStorage` keys can disappear on their own.
|
|
192
|
+
|
|
193
|
+
Cross-tab: `nextKey` is synchronous, so its read-modify-write is not atomic between tabs. Two tabs can read an empty store and write two keys for one operation, the last write wins. The guarantee holds within a single tab.
|
|
194
|
+
|
|
195
|
+
Multi-tenant: the fingerprint does not include headers, so two users or tenants sending the same body to the same path share a key. Pass `idempotencyScope` with the tenant or user id.
|
|
196
|
+
|
|
197
|
+
Several SSR instances: `memoryStorageSource` lives in one process, so a retry routed to another instance gets a new key. Use a source on top of a shared store.
|
|
198
|
+
|
|
199
|
+
## Requirements
|
|
200
|
+
|
|
201
|
+
Runs on Node.js 22.18+, modern browsers, Deno and Bun.
|
|
202
|
+
|
|
203
|
+
Needs a global `fetch`. If it's missing, `createClient` throws.
|
|
204
|
+
|
|
205
|
+
ESM only. CommonJS is not supported.
|
|
206
|
+
|
|
207
|
+
`crypto.randomUUID` is only needed when `withIdempotency` is in use with the built-in key generator. It is checked on the first mutating request.
|
|
208
|
+
|
|
209
|
+
## Modules
|
|
210
|
+
|
|
211
|
+
The library is split into modules. Bundle size depends on what you import.
|
|
212
|
+
|
|
213
|
+
| Module | What it exports |
|
|
214
|
+
| ------------------------- | --------------------------------------------------------------------------------------------------------- |
|
|
215
|
+
| `fetch-layers` | `createClient`, `ApiError`, `toApiError`, `ErrorBodyParser`, storages and public types |
|
|
216
|
+
| `fetch-layers/layers` | Factories for all built-in layers and idempotency key sources |
|
|
217
|
+
| `fetch-layers/auth` | Types `SessionProvider`, `RefreshResult`, `SessionExpiredReason`, `resetRefreshCircuit` |
|
|
218
|
+
| `fetch-layers/idempotency` | `IdempotencySource`, `IdempotencyContext`, `IdempotencyOutcome`, `createSessionSource`, `StorageSourceOptions`, `stableSerialize` |
|
|
219
|
+
| `fetch-layers/retry` | Only `withRetry` and its options |
|
|
220
|
+
| `fetch-layers/storage` | `StorageLike`, `createMemoryStorage`, `fromWebStorage` |
|
|
221
|
+
|
|
222
|
+
### Direct imports for a smaller bundle
|
|
223
|
+
|
|
224
|
+
`fetch-layers/layers` re-exports all three layers. `withRetry` and `withAuth` are also available from their own modules - the bundler won't pull the others in. The idempotency layer is imported from `fetch-layers/layers` together with its key sources.
|
|
225
|
+
|
|
226
|
+
```ts
|
|
227
|
+
import { withRetry } from 'fetch-layers/retry';
|
|
228
|
+
import { withAuth } from 'fetch-layers/auth';
|
|
229
|
+
import { withIdempotency, sessionStorageSource } from 'fetch-layers/layers';
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
`fetch-layers/layers` remains convenient for the common case: one import instead of three.
|
|
233
|
+
|
|
234
|
+
## How layers work
|
|
235
|
+
|
|
236
|
+
Every layer is a wrapper around a request function. The `wrap` method takes `next` and returns its own version. The library follows the Decorator pattern (GoF): it adds behavior while keeping the interface. The first layer in the array sees the request first, the last sees it last. Built-in layers run in order: idempotency, retries, auth. The transport receives the request last.
|
|
237
|
+
|
|
238
|
+
Each layer has a priority (`stage`). Higher number - earlier in the chain. Built-in priorities: `withIdempotency: 3`, `withRetry: 2`, `withAuth: 1`. To insert a custom layer between built-ins, use fractional values: `2.5` goes between idempotency and retries, `1.5` between retries and auth.
|
|
239
|
+
|
|
240
|
+
Layers without `stage` skip the order check. They can go anywhere in the array.
|
|
241
|
+
|
|
242
|
+
The order is not arbitrary. The idempotency key must be generated before the first attempt, otherwise every retry creates a new key and deduplication stops working. Auth must sit after retries, so a 401 goes to the auth layer, not to retry. `createClient` validates the order and throws with the name of the layer that breaks the rule.
|
|
243
|
+
|
|
244
|
+
Each client has its own state. The same `Layer` object can be passed to two `createClient` calls: each gets its own `RefreshManager`, its own warnings, its own counter. One client's state does not affect the other.
|
|
245
|
+
|
|
246
|
+
### Why layered architecture instead of hooks or interceptors
|
|
247
|
+
|
|
248
|
+
A layer controls the call: it can call `next` several times, catch an error and call again with different data, run code before and after. A callback can't do this: it receives data and returns it back. It does not decide when and how many times to call the next step.
|
|
249
|
+
|
|
250
|
+
A hook in ky or ofetch, an interceptor in axios - these are callbacks invoked at a fixed point: before the request or after the response. Each gets data and returns it.
|
|
251
|
+
|
|
252
|
+
`withRetry` calls `next` in a loop until it gets a successful response. `withAuth` catches 401, does a refresh separately, then calls `next` with a new token. `withIdempotency` wraps the whole call and clears the key only after the server confirms.
|
|
253
|
+
|
|
254
|
+
Hooks and interceptors can only change data on the way in and out. They don't describe the loop or the order of calls.
|
|
255
|
+
|
|
256
|
+
## Working with TanStack Query
|
|
257
|
+
|
|
258
|
+
fetch-layers plugs into `queryFn` and `mutationFn`.
|
|
259
|
+
|
|
260
|
+
```tsx
|
|
261
|
+
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
262
|
+
|
|
263
|
+
const client = createClient({
|
|
264
|
+
baseUrl: '/api',
|
|
265
|
+
layers: [
|
|
266
|
+
withIdempotency(sessionStorageSource()),
|
|
267
|
+
withAuth({ provider: sessionProvider }),
|
|
268
|
+
],
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
function useUser(id: string) {
|
|
272
|
+
return useQuery({
|
|
273
|
+
queryKey: ['user', id],
|
|
274
|
+
queryFn: ({ signal }) => client.get<User>(`/users/${id}`, { signal }),
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function useCreateOrder() {
|
|
279
|
+
const queryClient = useQueryClient();
|
|
280
|
+
|
|
281
|
+
return useMutation({
|
|
282
|
+
mutationFn: (order: Order) => client.post<Order>('/orders', order),
|
|
283
|
+
onSuccess: () => {
|
|
284
|
+
queryClient.invalidateQueries({ queryKey: ['orders'] });
|
|
285
|
+
},
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
`queryFn` gets `signal` from TanStack Query, fetch-layers accepts it and combines with its own timeout. Cancellation works both ways.
|
|
291
|
+
|
|
292
|
+
The main conflict is retry. TanStack Query has its own retry for `useQuery`, fetch-layers has its own for HTTP. If both are enabled, 3 attempts x 3 attempts = 9 requests. Keep retry in one place:
|
|
293
|
+
|
|
294
|
+
```ts
|
|
295
|
+
// Retry in fetch-layers, TanStack Query without retry.
|
|
296
|
+
const client = createClient({
|
|
297
|
+
baseUrl: '/api',
|
|
298
|
+
layers: [withRetry({ maxAttempts: 3 })],
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
useQuery({
|
|
302
|
+
queryKey: ['user', id],
|
|
303
|
+
queryFn: () => client.get<User>(`/users/${id}`),
|
|
304
|
+
retry: false,
|
|
305
|
+
});
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
Everything else works without adapters: `ApiError` propagates to `error`, `signal` is accepted as-is, DevTools shows `queryFn` calls unchanged.
|
|
309
|
+
|
|
310
|
+
## License
|
|
311
|
+
|
|
312
|
+
MIT. See [LICENSE](./LICENSE).
|
|
313
|
+
|
|
314
|
+
Changelog: [CHANGELOG.md](./CHANGELOG.md).
|