@r0hitsharma/http-client-react 0.12.0-rohit-fork-ci.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/DESIGN.md +378 -0
- package/README.md +427 -0
- package/dist/errors.d.ts +56 -0
- package/dist/errors.js +51 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +29 -0
- package/dist/middleware.d.ts +45 -0
- package/dist/middleware.js +25 -0
- package/dist/query-api.d.ts +114 -0
- package/dist/query-api.js +128 -0
- package/dist/query-client.d.ts +84 -0
- package/dist/query-client.js +152 -0
- package/dist/query-key.d.ts +50 -0
- package/dist/query-key.js +70 -0
- package/dist/tags.d.ts +28 -0
- package/dist/tags.js +53 -0
- package/dist/zod-response.d.ts +61 -0
- package/dist/zod-response.js +91 -0
- package/oxfmt.config.ts +5 -0
- package/oxlint.config.ts +5 -0
- package/package.json +49 -0
- package/src/deprecated.test.ts +27 -0
- package/src/errors.ts +74 -0
- package/src/index.tsx +100 -0
- package/src/middleware.test.ts +88 -0
- package/src/middleware.ts +84 -0
- package/src/query-api.test.ts +644 -0
- package/src/query-api.ts +512 -0
- package/src/query-api.types.test.ts +225 -0
- package/src/query-client.test.ts +315 -0
- package/src/query-client.ts +173 -0
- package/src/query-key.test.ts +121 -0
- package/src/query-key.ts +113 -0
- package/src/tags.ts +100 -0
- package/src/test-fixtures.ts +222 -0
- package/src/zod-response.ts +150 -0
- package/tsconfig.build.json +21 -0
- package/tsconfig.json +7 -0
- package/vitest.config.ts +11 -0
package/README.md
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
# @r0hitsharma/http-client-react
|
|
2
|
+
|
|
3
|
+
TanStack Query bindings for `@r0hitsharma/http-client-core`.
|
|
4
|
+
|
|
5
|
+
The generated OpenAPI `paths` type **is** the endpoint definition. Methods,
|
|
6
|
+
paths, params, request bodies, response types, and error bodies are all read off
|
|
7
|
+
it, so there is no second registry of endpoints to keep in step with the API.
|
|
8
|
+
See [DESIGN.md](./DESIGN.md) for the contract and its deliberate limits.
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm install @r0hitsharma/http-client-react @r0hitsharma/http-client-core '@tanstack/react-query@^5.89.0' react react-dom
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
`@tanstack/react-query` is a **peer** dependency, so the app owns the version and
|
|
17
|
+
the `QueryClient` this package's hooks and options talk to is the same instance
|
|
18
|
+
the app's own `useQuery` calls use. See [peer
|
|
19
|
+
dependencies](#peer-dependencies) for why the range starts at 5.89.0.
|
|
20
|
+
|
|
21
|
+
## Usage
|
|
22
|
+
|
|
23
|
+
### 1. Generate types and create the api
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
npx uikit-openapi-generate --schema openapi.json --output src/api.types.ts
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
// src/api.ts
|
|
31
|
+
import { createApiClient, createQueryApi } from '@r0hitsharma/http-client-react';
|
|
32
|
+
|
|
33
|
+
import type { paths } from './api.types';
|
|
34
|
+
|
|
35
|
+
const client = createApiClient<paths>('/api');
|
|
36
|
+
|
|
37
|
+
// Both the paths type and the tag vocabulary are inferred from the arguments.
|
|
38
|
+
// Do not pass type arguments explicitly: naming one turns inference off for the
|
|
39
|
+
// rest, and `TTag` silently widens to `string`.
|
|
40
|
+
export const api = createQueryApi(client, {
|
|
41
|
+
tags: ['positions', 'position', 'alerts'],
|
|
42
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### 2. Provide a QueryClient
|
|
46
|
+
|
|
47
|
+
```tsx
|
|
48
|
+
import { createQueryClient, HttpProvider } from '@r0hitsharma/http-client-react';
|
|
49
|
+
|
|
50
|
+
const queryClient = createQueryClient();
|
|
51
|
+
|
|
52
|
+
export function App() {
|
|
53
|
+
return (
|
|
54
|
+
<HttpProvider client={queryClient}>
|
|
55
|
+
<Dashboard />
|
|
56
|
+
</HttpProvider>
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`createQueryClient()` is a `QueryClient` with two defaults changed from
|
|
62
|
+
react-query's, both because react-query's are tuned for a document-shaped app
|
|
63
|
+
rather than a data-dense one:
|
|
64
|
+
|
|
65
|
+
| Default | Value | Why |
|
|
66
|
+
| --- | --- | --- |
|
|
67
|
+
| `refetchOnWindowFocus` | `false` | Alt-tabbing back to a dashboard should not reload every panel. Freshness is `staleTime` and explicit invalidation, which the app controls. |
|
|
68
|
+
| `retry` | status-aware | React-query retries every rejection three times, so a 422 costs four round trips to report a validation error the server decided on the first. |
|
|
69
|
+
|
|
70
|
+
The retry policy, exactly:
|
|
71
|
+
|
|
72
|
+
- **5xx** — retried. The request was well formed; the server was not well.
|
|
73
|
+
- **408, 425, 429** — retried. Request timeout, TLS early-data refusal, and rate
|
|
74
|
+
limiting are all transient conditions rather than bad requests.
|
|
75
|
+
- **every other 4xx** — not retried. A 401, a 404, a 422: repeating the request
|
|
76
|
+
unchanged produces the same answer more slowly.
|
|
77
|
+
- **anything below 400** — not retried. A 304 on the error path is a caching
|
|
78
|
+
problem, not a flaky one.
|
|
79
|
+
- **a rejection with no status at all** — retried. A dropped connection, a CORS
|
|
80
|
+
refusal, an abort, or a middleware that threw leaves no evidence except that
|
|
81
|
+
the request did not complete, and treating that as fatal makes one dropped
|
|
82
|
+
socket a visible error.
|
|
83
|
+
- **a `ZodResponseValidationError`** — not retried, the one exception to the line
|
|
84
|
+
above. `createZodResponseMiddleware` rejects after a 2xx arrived and parsed, so
|
|
85
|
+
the request *did* complete and the body will be the same on the next attempt.
|
|
86
|
+
|
|
87
|
+
Two retries, so with react-query's exponential `retryDelay` an error reaches the
|
|
88
|
+
screen about three seconds after the first failure. Mutations are not retried at
|
|
89
|
+
all — a `POST` that reached the server may have applied before the failure, and
|
|
90
|
+
this package cannot tell which.
|
|
91
|
+
|
|
92
|
+
With focus refetching off, **the app owns error recovery**. A query that has
|
|
93
|
+
exhausted its retries will not try again on its own while the tab stays open and
|
|
94
|
+
the connection stays up, and react-query keeps serving the last successful `data`
|
|
95
|
+
next to `status: 'error'` — so an expired session reads as current numbers unless
|
|
96
|
+
the screen says otherwise. Render the error and offer a refetch.
|
|
97
|
+
|
|
98
|
+
Nothing else is set. `staleTime` most of all: how long a screen may show a stale
|
|
99
|
+
number is a product decision, and a package-level guess would be wrong quietly.
|
|
100
|
+
|
|
101
|
+
#### Changing the defaults
|
|
102
|
+
|
|
103
|
+
`createQueryClient` takes react-query's own `QueryClientConfig` and every field
|
|
104
|
+
of it wins. The merge is per-option, so replacing one default keeps the rest:
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
// Keeps `refetchOnWindowFocus: false`; replaces only the retry policy.
|
|
108
|
+
const queryClient = createQueryClient({
|
|
109
|
+
defaultOptions: { queries: { retry: 5, staleTime: 30_000 } },
|
|
110
|
+
});
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
A `queries` key present with the value `undefined` is **not** an override — it
|
|
114
|
+
is dropped before the merge, and the default stands. So the else-branch of a
|
|
115
|
+
conditional override leaves the shipped policy in place rather than reverting it
|
|
116
|
+
to react-query's `retry ?? 3`:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
// `retry` is the package predicate whenever `cond` is false.
|
|
120
|
+
createQueryClient({
|
|
121
|
+
defaultOptions: { queries: { retry: cond ? false : undefined } },
|
|
122
|
+
});
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
To keep the status policy and change only how many times it asks again, or to
|
|
126
|
+
drop one error out of it, compose the exported predicates rather than restating
|
|
127
|
+
them:
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
import {
|
|
131
|
+
createQueryClient,
|
|
132
|
+
isRetryableError,
|
|
133
|
+
shouldRetryRequest,
|
|
134
|
+
} from '@r0hitsharma/http-client-react';
|
|
135
|
+
|
|
136
|
+
createQueryClient({
|
|
137
|
+
defaultOptions: {
|
|
138
|
+
queries: {
|
|
139
|
+
// Same statuses, five retries — six attempts. `failureCount` is the
|
|
140
|
+
// number of failures *before* this attempt, so it is 0 on the first.
|
|
141
|
+
retry: (failureCount, error) => failureCount < 5 && isRetryableError(error),
|
|
142
|
+
// Or: the shipped policy, minus one application-specific error.
|
|
143
|
+
// retry: (count, error) =>
|
|
144
|
+
// isSessionExpired(error) ? false : shouldRetryRequest(count, error),
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
`isRetryableHttpStatus(status)` is exported too, for a predicate built from
|
|
151
|
+
something other than an `HttpRequestError`.
|
|
152
|
+
|
|
153
|
+
#### Reporting errors once, centrally
|
|
154
|
+
|
|
155
|
+
Not shipped, deliberately: a `QueryCache.onError` that turns a failed query into
|
|
156
|
+
a toast. The wiring is three lines, but the useful half of it is the sink — your
|
|
157
|
+
notification system — and the `meta` field it reads has to be typed by
|
|
158
|
+
augmenting react-query's `Register` interface, which is a *global* declaration
|
|
159
|
+
an app can only make once. A package that made it would collide with the app's
|
|
160
|
+
own. So this stays a recipe rather than an export:
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
// src/query-client.ts
|
|
164
|
+
declare module '@tanstack/react-query' {
|
|
165
|
+
interface Register {
|
|
166
|
+
queryMeta: { errorMessage?: string };
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export const queryClient = createQueryClient({
|
|
171
|
+
queryCache: new QueryCache({
|
|
172
|
+
onError: (error, query) => {
|
|
173
|
+
// Only queries that opted in by declaring the message.
|
|
174
|
+
const message = query.meta?.errorMessage;
|
|
175
|
+
if (message) toast.error(message, { description: error.message });
|
|
176
|
+
},
|
|
177
|
+
}),
|
|
178
|
+
});
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
`meta` rides through on the per-call options: `api.queryOptions('get',
|
|
182
|
+
'/positions', undefined, { meta: { errorMessage: 'Could not load positions' } })`.
|
|
183
|
+
|
|
184
|
+
### 3. Query in a component
|
|
185
|
+
|
|
186
|
+
```tsx
|
|
187
|
+
import { isHttpRequestError } from '@r0hitsharma/http-client-react';
|
|
188
|
+
import { useQuery } from '@tanstack/react-query';
|
|
189
|
+
|
|
190
|
+
import { api } from './api';
|
|
191
|
+
|
|
192
|
+
function PositionPanel({ id }: { id: string }) {
|
|
193
|
+
const { data, isPending, error } = useQuery(
|
|
194
|
+
api.queryOptions(
|
|
195
|
+
'get',
|
|
196
|
+
'/positions/{id}',
|
|
197
|
+
{ params: { path: { id }, query: { expand: 'collateral' } } },
|
|
198
|
+
{ tags: ['position'], staleTime: 30_000 },
|
|
199
|
+
),
|
|
200
|
+
);
|
|
201
|
+
|
|
202
|
+
if (isPending) return <LoadingIndicator />;
|
|
203
|
+
if (error) {
|
|
204
|
+
// `status` and the parsed error body are only on HTTP failures; a transport
|
|
205
|
+
// error or a validation middleware rejects with a plain Error.
|
|
206
|
+
return (
|
|
207
|
+
<ErrorState
|
|
208
|
+
message={isHttpRequestError(error) ? `HTTP ${error.status}` : error.message}
|
|
209
|
+
/>
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return <PositionSummary position={data} />;
|
|
214
|
+
}
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
`data` is typed from the operation's 2xx response, the `params` object is typed
|
|
218
|
+
from its parameters, and the query key is derived — `['get', '/positions/{id}',
|
|
219
|
+
{ path: { id }, query: { expand: 'collateral' } }]` — so two components asking
|
|
220
|
+
for the same thing share one cache entry regardless of how they spell the init.
|
|
221
|
+
|
|
222
|
+
### 4. Mutate, and invalidate by tag
|
|
223
|
+
|
|
224
|
+
```tsx
|
|
225
|
+
import { useMutation } from '@tanstack/react-query';
|
|
226
|
+
|
|
227
|
+
import { api } from './api';
|
|
228
|
+
|
|
229
|
+
function ClosePositionButton({ id }: { id: string }) {
|
|
230
|
+
const { mutate, isPending } = useMutation(
|
|
231
|
+
api.mutationOptions('post', '/positions/{id}/close', {
|
|
232
|
+
// A tag, or a callback that derives tags from the mutation's own result.
|
|
233
|
+
invalidates: ['position', (closed) => (closed.liquidated ? 'alerts' : [])],
|
|
234
|
+
}),
|
|
235
|
+
);
|
|
236
|
+
|
|
237
|
+
return (
|
|
238
|
+
<Button
|
|
239
|
+
disabled={isPending}
|
|
240
|
+
onClick={() => mutate({ params: { path: { id } } })}
|
|
241
|
+
>
|
|
242
|
+
Close
|
|
243
|
+
</Button>
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
The mutation variables are the operation's init, so the body and params are
|
|
249
|
+
typed. On success, every query registered under an invalidated tag is
|
|
250
|
+
invalidated through the `QueryClient` react-query passes to the mutation — no
|
|
251
|
+
`useQueryClient` call and no key factory at the call site.
|
|
252
|
+
|
|
253
|
+
### 5. Middleware, including response validation
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
import {
|
|
257
|
+
createApiClient,
|
|
258
|
+
createQueryApi,
|
|
259
|
+
createZodResponseMiddleware,
|
|
260
|
+
type QueryApiMiddleware,
|
|
261
|
+
} from '@r0hitsharma/http-client-react';
|
|
262
|
+
|
|
263
|
+
import openApiDocument from '../openapi.json';
|
|
264
|
+
import type { paths } from './api.types';
|
|
265
|
+
|
|
266
|
+
const logSlowRequests: QueryApiMiddleware = async (ctx, next) => {
|
|
267
|
+
const startedAt = performance.now();
|
|
268
|
+
try {
|
|
269
|
+
return await next();
|
|
270
|
+
} finally {
|
|
271
|
+
const elapsed = performance.now() - startedAt;
|
|
272
|
+
if (elapsed > 1_000) {
|
|
273
|
+
console.warn(`slow ${ctx.method} ${ctx.path}: ${Math.round(elapsed)}ms`);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
export const api = createQueryApi(createApiClient<paths>('/api'), {
|
|
279
|
+
tags: ['positions', 'position', 'alerts'],
|
|
280
|
+
middleware: [
|
|
281
|
+
logSlowRequests,
|
|
282
|
+
createZodResponseMiddleware({
|
|
283
|
+
document: openApiDocument,
|
|
284
|
+
schemas: { 'get /positions/{id}': 'Position' },
|
|
285
|
+
// Report drift instead of breaking the screen. Omit to reject instead.
|
|
286
|
+
onInvalid: (error) => console.warn(error.message, error.issues),
|
|
287
|
+
}),
|
|
288
|
+
],
|
|
289
|
+
});
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
Middleware is onion-style over the *parsed result*: `[a, b]` means `a` runs
|
|
293
|
+
before `b` on the way in and after it on the way out. A per-call
|
|
294
|
+
`middleware: [...]` on `queryOptions`/`mutationOptions` is appended innermost,
|
|
295
|
+
which is how you opt one query into response validation rather than all of them.
|
|
296
|
+
For middleware that needs the raw `Request`/`Response`, use `openapi-fetch`'s own
|
|
297
|
+
`client.use()`.
|
|
298
|
+
|
|
299
|
+
### Targeting the cache directly
|
|
300
|
+
|
|
301
|
+
```ts
|
|
302
|
+
// Exactly one query.
|
|
303
|
+
queryClient.getQueryData(api.queryKey('get', '/positions/{id}', { params: { path: { id } } }));
|
|
304
|
+
|
|
305
|
+
// Every cached variant of an endpoint — the key's first two elements are the
|
|
306
|
+
// operation, and react-query prefix-matches.
|
|
307
|
+
await queryClient.invalidateQueries({ queryKey: ['get', '/positions'] });
|
|
308
|
+
|
|
309
|
+
// Everything under a tag.
|
|
310
|
+
await api.invalidateTags(queryClient, ['positions']);
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
`sanitizeQueryInit` and `buildQueryApiKey` are exported for anything that needs
|
|
314
|
+
to derive a key outside an api instance.
|
|
315
|
+
|
|
316
|
+
### Prefetching: pass `queryOptions`, never `queryKey`
|
|
317
|
+
|
|
318
|
+
`api.queryKey(…)` targets an entry that already exists. `api.queryOptions(…)`
|
|
319
|
+
*describes* one. Prefetching creates an entry, so it takes the options:
|
|
320
|
+
|
|
321
|
+
```ts
|
|
322
|
+
// Right: one argument, and it is the whole options object.
|
|
323
|
+
await queryClient.prefetchQuery(
|
|
324
|
+
api.queryOptions(
|
|
325
|
+
'get',
|
|
326
|
+
'/positions/{id}',
|
|
327
|
+
{ params: { path: { id } } },
|
|
328
|
+
{ tags: ['position'], staleTime: 30_000 },
|
|
329
|
+
),
|
|
330
|
+
);
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
```ts
|
|
334
|
+
// Wrong, and it typechecks, and it warms the cache, and it still costs you.
|
|
335
|
+
await queryClient.prefetchQuery({
|
|
336
|
+
queryKey: api.queryKey('get', '/positions/{id}', { params: { path: { id } } }),
|
|
337
|
+
queryFn: () => fetch(`/api/positions/${id}`).then((r) => r.json()),
|
|
338
|
+
});
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
The key is identical in both, so the entry lands where the component will look
|
|
342
|
+
for it and the prefetch appears to work. What the second form drops is
|
|
343
|
+
everything else the options carry:
|
|
344
|
+
|
|
345
|
+
- **`staleTime`.** Absent, it falls back to react-query's `0`, so the entry is
|
|
346
|
+
stale the instant it is written. The component mounts, reads it, and refetches
|
|
347
|
+
immediately — you paid for the request and saved nothing. This is the failure
|
|
348
|
+
that looks most like success: data does appear, just after a second round
|
|
349
|
+
trip.
|
|
350
|
+
- **The middleware chain.** A hand-written `queryFn` bypasses the api instance
|
|
351
|
+
entirely, so response validation, auth headers, and every other middleware do
|
|
352
|
+
not run. The cached data was never checked, and the component that reads it
|
|
353
|
+
cannot tell.
|
|
354
|
+
- **`tags`.** Registration is a side effect of building the options, so an entry
|
|
355
|
+
prefetched around them belongs to no tag and `invalidateTags` skips it
|
|
356
|
+
silently — see [the registry's boundary](./DESIGN.md#the-registrys-boundary).
|
|
357
|
+
- **The error type.** `api.queryOptions` rejects with `HttpRequestError`; a raw
|
|
358
|
+
`fetch` resolves a 404 into whatever `r.json()` makes of the error body, and
|
|
359
|
+
the entry caches that as *data*.
|
|
360
|
+
|
|
361
|
+
The same rule holds for `fetchQuery` and `ensureQueryData`, and for a router
|
|
362
|
+
loader that warms the cache before a route renders. If you find yourself writing
|
|
363
|
+
a `queryFn` next to an `api.queryKey(…)` call, the options object you want
|
|
364
|
+
already exists.
|
|
365
|
+
|
|
366
|
+
One caveat on the last line: `invalidateTags` reaches only the endpoints some
|
|
367
|
+
`api.queryOptions(…, { tags })` call has registered. An entry written straight
|
|
368
|
+
through `setQueryData`, or restored by SSR/persisted-cache hydration, is cached
|
|
369
|
+
under a perfectly good key that the tag has never heard of, and the invalidation
|
|
370
|
+
skips it silently. Register the endpoint once at module scope, or invalidate by
|
|
371
|
+
key prefix — see [the registry's
|
|
372
|
+
boundary](./DESIGN.md#the-registrys-boundary).
|
|
373
|
+
|
|
374
|
+
## API surface
|
|
375
|
+
|
|
376
|
+
| Export | What it does |
|
|
377
|
+
| --- | --- |
|
|
378
|
+
| `createQueryApi(client, options?)` | Binds a TanStack Query surface to an `openapi-fetch` client |
|
|
379
|
+
| `api.queryOptions(method, path, init?, options?)` | `queryOptions` for a GET/HEAD operation, with a derived key |
|
|
380
|
+
| `api.mutationOptions(method, path, options?)` | `mutationOptions` for a POST/PUT/PATCH/DELETE operation |
|
|
381
|
+
| `api.queryKey(method, path, init?)` | The derived, branded query key for an operation |
|
|
382
|
+
| `api.tagFilter(tag)` | A react-query filter matching every query under a tag |
|
|
383
|
+
| `api.invalidateTags(queryClient, tags)` | Invalidates every query under the given tags |
|
|
384
|
+
| `api.taggedEndpoints(tag)` | The `${method} ${path}` tokens registered under a tag |
|
|
385
|
+
| `createZodResponseMiddleware(options)` | Validates responses against the OpenAPI document |
|
|
386
|
+
| `ZodResponseValidationError` / `isZodResponseValidationError` | The validation failure that middleware raises, and its guard |
|
|
387
|
+
| `HttpRequestError` / `isHttpRequestError` | The typed failure carrying `status` and the parsed error body |
|
|
388
|
+
| `sanitizeQueryInit` / `buildQueryApiKey` / `canonicalizeQueryKeyValue` | The key-derivation primitives |
|
|
389
|
+
| `composeMiddleware` | The middleware combinator, for composing chains outside an api |
|
|
390
|
+
| `createQueryClient(config?)` | A `QueryClient` with dashboard defaults; `config` overrides per option |
|
|
391
|
+
| `shouldRetryRequest(failureCount, error)` | The default retry predicate, for wrapping |
|
|
392
|
+
| `isRetryableError(error)` / `isRetryableHttpStatus(status)` | The retry policy's two halves, for building a custom predicate |
|
|
393
|
+
| `HttpProvider` | `QueryClientProvider` wrapper, defaulting to an internal client |
|
|
394
|
+
| `createQueryOptions` | **Deprecated.** Hand-written key + fn shim; use `api.queryOptions` |
|
|
395
|
+
|
|
396
|
+
## Not in v1
|
|
397
|
+
|
|
398
|
+
Optimistic updates, cache updaters, cross-tab cache sync, infinite queries, and
|
|
399
|
+
`POST`-backed reads are deliberately out of scope — see
|
|
400
|
+
[DESIGN.md](./DESIGN.md#deliberately-out-of-v1). The mock layer is a separate
|
|
401
|
+
package: [http-client-msw](../http-client-msw) keys its handlers off the same
|
|
402
|
+
`paths` type, so a fixture and the request it stands in for are described by one
|
|
403
|
+
source.
|
|
404
|
+
|
|
405
|
+
## Peer dependencies
|
|
406
|
+
|
|
407
|
+
- `react`, `react-dom` — `^19.0.0`
|
|
408
|
+
- `@tanstack/react-query` — `^5.89.0`
|
|
409
|
+
|
|
410
|
+
The react-query floor is not arbitrary. `mutationOptions` invalidates tags
|
|
411
|
+
through the `QueryClient` react-query hands to the mutation callback, which means
|
|
412
|
+
it needs the four-argument `onSuccess(data, variables, onMutateResult, context)`
|
|
413
|
+
signature and `context.client`. Both arrived in **5.89.0**; the release before it
|
|
414
|
+
(5.87.4) passes three arguments and no client, so the package does not typecheck
|
|
415
|
+
against it. Anything from 5.89.0 up works — the package is developed against the
|
|
416
|
+
latest 5.x.
|
|
417
|
+
|
|
418
|
+
Keeping react-query a peer rather than a dependency is what guarantees one
|
|
419
|
+
`QueryClient` and one cache: two copies in the module graph would give the
|
|
420
|
+
`HttpProvider` and the app's own hooks separate caches.
|
|
421
|
+
|
|
422
|
+
## See also
|
|
423
|
+
|
|
424
|
+
- [http-client-core](../http-client-core) for the client factory and the
|
|
425
|
+
OpenAPI/zod helpers
|
|
426
|
+
- [http-client-msw](../http-client-msw) for the mock layer keyed off the same
|
|
427
|
+
`paths` type
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `openapi-fetch` resolves both outcomes of a request into `{ data, error }`,
|
|
3
|
+
* so a 404 is a fulfilled promise. TanStack Query only treats a *rejected*
|
|
4
|
+
* query function as a failure, so the query layer has to convert one into the
|
|
5
|
+
* other. This is the carrier for that conversion: it keeps the HTTP status and
|
|
6
|
+
* the parsed error body instead of flattening the failure to a message string.
|
|
7
|
+
*/
|
|
8
|
+
export declare class HttpRequestError<TBody = unknown> extends Error {
|
|
9
|
+
readonly name = "HttpRequestError";
|
|
10
|
+
/** Lowercase OpenAPI method (`get`, `post`, …) that failed. */
|
|
11
|
+
readonly method: string;
|
|
12
|
+
/** The OpenAPI path template, braces intact (`/users/{id}`). */
|
|
13
|
+
readonly path: string;
|
|
14
|
+
readonly status: number;
|
|
15
|
+
readonly statusText: string;
|
|
16
|
+
/**
|
|
17
|
+
* The response body parsed by `openapi-fetch`, typed from the operation's
|
|
18
|
+
* error responses — and `| undefined`, because a failure need not have one: a
|
|
19
|
+
* 5xx from a proxy, or any non-2xx with an empty body, leaves nothing to
|
|
20
|
+
* parse. Declaring it as `TBody` alone would let a consumer read through to a
|
|
21
|
+
* property of a body that is not there.
|
|
22
|
+
*/
|
|
23
|
+
readonly body: TBody | undefined;
|
|
24
|
+
readonly response: Response;
|
|
25
|
+
constructor(init: {
|
|
26
|
+
method: string;
|
|
27
|
+
path: string;
|
|
28
|
+
body: TBody | undefined;
|
|
29
|
+
response: Response;
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* What {@link isHttpRequestError} narrows `TValue` to: the `HttpRequestError`
|
|
34
|
+
* member `TValue` already declares, so the body type the operation described
|
|
35
|
+
* survives the guard, and a bare `HttpRequestError` when `TValue` declares none
|
|
36
|
+
* — a `catch` binding, where no body type is knowable.
|
|
37
|
+
*/
|
|
38
|
+
type NarrowedHttpRequestError<TValue> = [
|
|
39
|
+
Extract<TValue, HttpRequestError<unknown>>
|
|
40
|
+
] extends [never] ? HttpRequestError<unknown> : Extract<TValue, HttpRequestError<unknown>>;
|
|
41
|
+
/**
|
|
42
|
+
* Narrows a caught value to {@link HttpRequestError}.
|
|
43
|
+
*
|
|
44
|
+
* Matches on `name` rather than `instanceof` so the guard still holds when a
|
|
45
|
+
* consumer ends up with two copies of this package in its module graph (a
|
|
46
|
+
* bundled app plus a linked workspace build, for instance).
|
|
47
|
+
*
|
|
48
|
+
* The body type is *derived* from the argument rather than taken as a type
|
|
49
|
+
* parameter. A runtime check on `name` can say nothing about the body's shape,
|
|
50
|
+
* so a `TBody` parameter would have let a call site name any type it liked and
|
|
51
|
+
* get it back unchecked; deriving it means narrowing a
|
|
52
|
+
* `QueryApiError<TErrorBody>` yields that operation's own error body, and
|
|
53
|
+
* narrowing an `unknown` yields `unknown` — which is the truth in both cases.
|
|
54
|
+
*/
|
|
55
|
+
export declare function isHttpRequestError<TValue>(value: TValue): value is TValue & NarrowedHttpRequestError<TValue>;
|
|
56
|
+
export {};
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `openapi-fetch` resolves both outcomes of a request into `{ data, error }`,
|
|
3
|
+
* so a 404 is a fulfilled promise. TanStack Query only treats a *rejected*
|
|
4
|
+
* query function as a failure, so the query layer has to convert one into the
|
|
5
|
+
* other. This is the carrier for that conversion: it keeps the HTTP status and
|
|
6
|
+
* the parsed error body instead of flattening the failure to a message string.
|
|
7
|
+
*/
|
|
8
|
+
export class HttpRequestError extends Error {
|
|
9
|
+
name = 'HttpRequestError';
|
|
10
|
+
/** Lowercase OpenAPI method (`get`, `post`, …) that failed. */
|
|
11
|
+
method;
|
|
12
|
+
/** The OpenAPI path template, braces intact (`/users/{id}`). */
|
|
13
|
+
path;
|
|
14
|
+
status;
|
|
15
|
+
statusText;
|
|
16
|
+
/**
|
|
17
|
+
* The response body parsed by `openapi-fetch`, typed from the operation's
|
|
18
|
+
* error responses — and `| undefined`, because a failure need not have one: a
|
|
19
|
+
* 5xx from a proxy, or any non-2xx with an empty body, leaves nothing to
|
|
20
|
+
* parse. Declaring it as `TBody` alone would let a consumer read through to a
|
|
21
|
+
* property of a body that is not there.
|
|
22
|
+
*/
|
|
23
|
+
body;
|
|
24
|
+
response;
|
|
25
|
+
constructor(init) {
|
|
26
|
+
super(`${init.method.toUpperCase()} ${init.path} failed with status ${init.response.status}`);
|
|
27
|
+
this.method = init.method;
|
|
28
|
+
this.path = init.path;
|
|
29
|
+
this.status = init.response.status;
|
|
30
|
+
this.statusText = init.response.statusText;
|
|
31
|
+
this.body = init.body;
|
|
32
|
+
this.response = init.response;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Narrows a caught value to {@link HttpRequestError}.
|
|
37
|
+
*
|
|
38
|
+
* Matches on `name` rather than `instanceof` so the guard still holds when a
|
|
39
|
+
* consumer ends up with two copies of this package in its module graph (a
|
|
40
|
+
* bundled app plus a linked workspace build, for instance).
|
|
41
|
+
*
|
|
42
|
+
* The body type is *derived* from the argument rather than taken as a type
|
|
43
|
+
* parameter. A runtime check on `name` can say nothing about the body's shape,
|
|
44
|
+
* so a `TBody` parameter would have let a call site name any type it liked and
|
|
45
|
+
* get it back unchecked; deriving it means narrowing a
|
|
46
|
+
* `QueryApiError<TErrorBody>` yields that operation's own error body, and
|
|
47
|
+
* narrowing an `unknown` yields `unknown` — which is the truth in both cases.
|
|
48
|
+
*/
|
|
49
|
+
export function isHttpRequestError(value) {
|
|
50
|
+
return value instanceof Error && value.name === 'HttpRequestError';
|
|
51
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type QueryClient } from '@tanstack/react-query';
|
|
2
|
+
import type { PropsWithChildren } from 'react';
|
|
3
|
+
export { createApiClient } from '@r0hitsharma/http-client-core';
|
|
4
|
+
export type { ApiClient, ApiClientOptions, JsonSchema, } from '@r0hitsharma/http-client-core';
|
|
5
|
+
export { createQueryApi } from './query-api.js';
|
|
6
|
+
export type { MutationInvalidation, QueryApi, QueryApiCallOptions, QueryApiError, QueryApiKeyFn, QueryApiMutationCallOptions, QueryApiMutationMethod, QueryApiMutationOptionsFn, QueryApiOptions, QueryApiPaths, QueryApiQueryMethod, QueryApiQueryOptionsFn, } from './query-api.js';
|
|
7
|
+
export { HttpRequestError, isHttpRequestError } from './errors.js';
|
|
8
|
+
export { composeMiddleware } from './middleware.js';
|
|
9
|
+
export type { QueryApiMiddleware, QueryApiNext, QueryApiOperationType, QueryApiRequestContext, } from './middleware.js';
|
|
10
|
+
export { buildQueryApiKey, canonicalizeQueryKeyValue, operationToken, sanitizeQueryInit, } from './query-key.js';
|
|
11
|
+
export type { QueryApiKey, SanitizedQueryInit } from './query-key.js';
|
|
12
|
+
export { createQueryClient, isRetryableError, isRetryableHttpStatus, shouldRetryRequest, } from './query-client.js';
|
|
13
|
+
export { createZodResponseMiddleware, isZodResponseValidationError, ZodResponseValidationError, } from './zod-response.js';
|
|
14
|
+
export type { ResponseSchemaSource, ResponseValidationIssue, ZodResponseMiddlewareOptions, } from './zod-response.js';
|
|
15
|
+
export type HttpProviderProps = PropsWithChildren<{
|
|
16
|
+
client?: QueryClient;
|
|
17
|
+
}>;
|
|
18
|
+
export declare function HttpProvider({ client, children }: HttpProviderProps): import("react").JSX.Element;
|
|
19
|
+
/**
|
|
20
|
+
* @deprecated Use `createQueryApi(client).queryOptions(method, path, init)`
|
|
21
|
+
* instead: it derives the query key from the operation, types the result from
|
|
22
|
+
* the OpenAPI response, and rejects with a typed error. This shim keeps working
|
|
23
|
+
* for the hand-written query keys that predate it.
|
|
24
|
+
*/
|
|
25
|
+
export declare function createQueryOptions<TData>(queryKey: readonly unknown[], queryFn: () => Promise<TData>): import("@tanstack/query-core").OmitKeyof<import("@tanstack/react-query").UseQueryOptions<TData, Error, TData, readonly unknown[]>, "queryFn"> & {
|
|
26
|
+
queryFn?: import("@tanstack/query-core").QueryFunction<TData, readonly unknown[], never> | undefined;
|
|
27
|
+
} & import("@tanstack/query-core").QueryKeyWithDataTag<readonly unknown[], TData, Error>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { queryOptions, QueryClientProvider, } from '@tanstack/react-query';
|
|
3
|
+
import { createQueryClient } from './query-client.js';
|
|
4
|
+
export { createApiClient } from '@r0hitsharma/http-client-core';
|
|
5
|
+
export { createQueryApi } from './query-api.js';
|
|
6
|
+
export { HttpRequestError, isHttpRequestError } from './errors.js';
|
|
7
|
+
export { composeMiddleware } from './middleware.js';
|
|
8
|
+
export { buildQueryApiKey, canonicalizeQueryKeyValue, operationToken, sanitizeQueryInit, } from './query-key.js';
|
|
9
|
+
export { createQueryClient, isRetryableError, isRetryableHttpStatus, shouldRetryRequest, } from './query-client.js';
|
|
10
|
+
export { createZodResponseMiddleware, isZodResponseValidationError, ZodResponseValidationError, } from './zod-response.js';
|
|
11
|
+
/**
|
|
12
|
+
* The client `HttpProvider` falls back to when the app does not pass one. A
|
|
13
|
+
* single module-scoped instance, so every consumer of the fallback shares one
|
|
14
|
+
* cache — but prefer creating it in the app: the fallback cannot be reset
|
|
15
|
+
* between tests and cannot be reached for `setQueryData` before render.
|
|
16
|
+
*/
|
|
17
|
+
const defaultQueryClient = createQueryClient();
|
|
18
|
+
export function HttpProvider({ client, children }) {
|
|
19
|
+
return (_jsx(QueryClientProvider, { client: client ?? defaultQueryClient, children: children }));
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* @deprecated Use `createQueryApi(client).queryOptions(method, path, init)`
|
|
23
|
+
* instead: it derives the query key from the operation, types the result from
|
|
24
|
+
* the OpenAPI response, and rejects with a typed error. This shim keeps working
|
|
25
|
+
* for the hand-written query keys that predate it.
|
|
26
|
+
*/
|
|
27
|
+
export function createQueryOptions(queryKey, queryFn) {
|
|
28
|
+
return queryOptions({ queryKey, queryFn });
|
|
29
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/** Which half of the API a request came from. */
|
|
2
|
+
export type QueryApiOperationType = 'query' | 'mutation';
|
|
3
|
+
/**
|
|
4
|
+
* What a middleware sees. `init` is the init as it will be handed to
|
|
5
|
+
* `openapi-fetch` — the caller's init plus the abort `signal` react-query
|
|
6
|
+
* supplies — not the sanitized cache-key form.
|
|
7
|
+
*/
|
|
8
|
+
export type QueryApiRequestContext = {
|
|
9
|
+
/** Lowercase OpenAPI method (`get`, `post`, …). */
|
|
10
|
+
readonly method: string;
|
|
11
|
+
/** The OpenAPI path template, braces intact (`/users/{id}`). */
|
|
12
|
+
readonly path: string;
|
|
13
|
+
readonly operationType: QueryApiOperationType;
|
|
14
|
+
readonly init: Record<string, unknown> | undefined;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Invokes the rest of the chain. Called with no argument to pass the context
|
|
18
|
+
* through unchanged, or with a replacement to rewrite the request downstream.
|
|
19
|
+
*/
|
|
20
|
+
export type QueryApiNext = (ctx?: QueryApiRequestContext) => Promise<unknown>;
|
|
21
|
+
/**
|
|
22
|
+
* Onion-style middleware over the *parsed result* of a request, not over
|
|
23
|
+
* `Request`/`Response`. That is the altitude for response validation, logging
|
|
24
|
+
* and timing, rewriting the request on the way in (`next(ctx)`), reshaping the
|
|
25
|
+
* result on the way out, and short-circuiting with a substitute result by never
|
|
26
|
+
* calling `next` at all.
|
|
27
|
+
*
|
|
28
|
+
* **Not retries.** `next` is single-use per invocation — a second call rejects —
|
|
29
|
+
* so a middleware cannot re-issue the request it is wrapping. Retrying belongs
|
|
30
|
+
* either to react-query, whose `retry`/`retryDelay` re-invoke the whole chain
|
|
31
|
+
* from the top, or to the `fetch` implementation handed to `createApiClient`,
|
|
32
|
+
* which owns the actual HTTP call. `openapi-fetch`'s own `use()` middleware
|
|
33
|
+
* remains available on the client for anything that needs the raw HTTP objects.
|
|
34
|
+
*/
|
|
35
|
+
export type QueryApiMiddleware = (ctx: QueryApiRequestContext, next: QueryApiNext) => Promise<unknown>;
|
|
36
|
+
type TerminalHandler = (ctx: QueryApiRequestContext) => Promise<unknown>;
|
|
37
|
+
/**
|
|
38
|
+
* Folds `middleware` around `terminal`, outermost first: given `[a, b]`, `a`
|
|
39
|
+
* runs before `b` on the way in and after `b` on the way out.
|
|
40
|
+
*
|
|
41
|
+
* Each composed handler is single-use per invocation — calling `next()` twice
|
|
42
|
+
* from one middleware rejects rather than issuing the request twice.
|
|
43
|
+
*/
|
|
44
|
+
export declare function composeMiddleware(middleware: readonly QueryApiMiddleware[], terminal: TerminalHandler): TerminalHandler;
|
|
45
|
+
export {};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Folds `middleware` around `terminal`, outermost first: given `[a, b]`, `a`
|
|
3
|
+
* runs before `b` on the way in and after `b` on the way out.
|
|
4
|
+
*
|
|
5
|
+
* Each composed handler is single-use per invocation — calling `next()` twice
|
|
6
|
+
* from one middleware rejects rather than issuing the request twice.
|
|
7
|
+
*/
|
|
8
|
+
export function composeMiddleware(middleware, terminal) {
|
|
9
|
+
if (middleware.length === 0)
|
|
10
|
+
return terminal;
|
|
11
|
+
return (ctx) => {
|
|
12
|
+
let called = -1;
|
|
13
|
+
const dispatch = (index, current) => {
|
|
14
|
+
if (index <= called) {
|
|
15
|
+
return Promise.reject(new Error('http-client-react: middleware called next() more than once'));
|
|
16
|
+
}
|
|
17
|
+
called = index;
|
|
18
|
+
const handler = middleware[index];
|
|
19
|
+
if (!handler)
|
|
20
|
+
return terminal(current);
|
|
21
|
+
return handler(current, (nextCtx) => dispatch(index + 1, nextCtx ?? current));
|
|
22
|
+
};
|
|
23
|
+
return dispatch(0, ctx);
|
|
24
|
+
};
|
|
25
|
+
}
|