@molecule/app-query-react 1.1.6 → 1.2.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/README.md +163 -1
- package/dist/index.d.ts +50 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +50 -0
- package/dist/resource.d.ts +94 -0
- package/dist/resource.d.ts.map +1 -0
- package/dist/resource.js +103 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
|
|
|
3
3
|
Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
|
|
4
4
|
Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
|
|
5
5
|
To change this document, edit the module-level JSDoc in src/index.ts.
|
|
6
|
-
Generated: 2026-11-
|
|
6
|
+
Generated: 2026-11-11T18:03:13.387Z
|
|
7
7
|
-->
|
|
8
8
|
|
|
9
9
|
# @molecule/app-query-react
|
|
@@ -220,6 +220,54 @@ function Retry({ principal }: { principal: string }) {
|
|
|
220
220
|
}
|
|
221
221
|
```
|
|
222
222
|
|
|
223
|
+
One API resource described once, for every page that reads or changes it.
|
|
224
|
+
`createQueryResource` returns the list and detail reads as `useQuery` options and the writes
|
|
225
|
+
as functions that put the server's record into the cache and fetch the lists on screen again,
|
|
226
|
+
so a page never mirrors a response into `useState`. A flag the API models as a sub-path
|
|
227
|
+
(`POST /invoices/:id/flag`, `DELETE` to clear it) is `toggle`, which resolves with the saved
|
|
228
|
+
record and is the `commit` of `useOptimisticValue`.
|
|
229
|
+
|
|
230
|
+
```tsx
|
|
231
|
+
import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
|
|
232
|
+
import { createQueryResource, useQuery } from '@molecule/app-query-react'
|
|
233
|
+
import { useAuth, useOptimisticValue } from '@molecule/app-react'
|
|
234
|
+
|
|
235
|
+
interface Invoice {
|
|
236
|
+
id: string
|
|
237
|
+
number: string
|
|
238
|
+
flagged: boolean
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export const invoices = createQueryResource<Invoice>({
|
|
242
|
+
name: 'invoices',
|
|
243
|
+
path: '/invoices',
|
|
244
|
+
http: getClient,
|
|
245
|
+
readList: (response) => unwrapList<Invoice>(response),
|
|
246
|
+
readOne: (response) => unwrapSingle<Invoice>(response),
|
|
247
|
+
})
|
|
248
|
+
|
|
249
|
+
function InvoicePage({ id }: { id: string }) {
|
|
250
|
+
const { user } = useAuth<{ id: string }>()
|
|
251
|
+
const viewer = user ? String(user.id) : 'anonymous'
|
|
252
|
+
const { data: invoice, status } = useQuery(invoices.detail(viewer, id))
|
|
253
|
+
if (status === 'idle' || status === 'loading') return <p role=status>…</p>
|
|
254
|
+
if (!invoice) return <p role=alert>…</p>
|
|
255
|
+
return <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function FlagButton({ invoice, viewer }: { invoice: Invoice; viewer: string }) {
|
|
259
|
+
const flag = useOptimisticValue({
|
|
260
|
+
value: invoice.flagged,
|
|
261
|
+
commit: async (on) => (await invoices.toggle(viewer, invoice.id, 'flag', on)).flagged,
|
|
262
|
+
})
|
|
263
|
+
return (
|
|
264
|
+
<button type=button aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
|
|
265
|
+
{invoice.number}
|
|
266
|
+
</button>
|
|
267
|
+
)
|
|
268
|
+
}
|
|
269
|
+
```
|
|
270
|
+
|
|
223
271
|
## Type
|
|
224
272
|
|
|
225
273
|
`feature`
|
|
@@ -235,6 +283,96 @@ npm install -D @types/react
|
|
|
235
283
|
|
|
236
284
|
### Interfaces
|
|
237
285
|
|
|
286
|
+
#### `ResourceResponse`
|
|
287
|
+
|
|
288
|
+
The part of an HTTP response a resource reads.
|
|
289
|
+
|
|
290
|
+
```typescript
|
|
291
|
+
interface ResourceResponse {
|
|
292
|
+
/** The parsed response body. */
|
|
293
|
+
data: unknown
|
|
294
|
+
}
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
#### `ResourceHttp`
|
|
298
|
+
|
|
299
|
+
The HTTP client a resource calls: the app's own bonded client (`getClient()` from
|
|
300
|
+
`@molecule/app-http`) has this shape. Only what a resource uses is named here.
|
|
301
|
+
|
|
302
|
+
```typescript
|
|
303
|
+
interface ResourceHttp {
|
|
304
|
+
/** Reads `path`; `signal` cancels it and `params` become the query string. */
|
|
305
|
+
get(
|
|
306
|
+
path: string,
|
|
307
|
+
options?: { signal?: AbortSignal; params?: Record<string, unknown> },
|
|
308
|
+
): Promise<ResourceResponse>
|
|
309
|
+
/** Creates at `path`. */
|
|
310
|
+
post(path: string, body?: unknown): Promise<ResourceResponse>
|
|
311
|
+
/** Replaces at `path`. */
|
|
312
|
+
put(path: string, body?: unknown): Promise<ResourceResponse>
|
|
313
|
+
/** Changes part of the record at `path`. */
|
|
314
|
+
patch(path: string, body?: unknown): Promise<ResourceResponse>
|
|
315
|
+
/** Removes at `path`. */
|
|
316
|
+
delete(path: string): Promise<ResourceResponse>
|
|
317
|
+
}
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
#### `QueryResourceConfig`
|
|
321
|
+
|
|
322
|
+
What {@link createQueryResource} needs to know about one resource.
|
|
323
|
+
|
|
324
|
+
```typescript
|
|
325
|
+
interface QueryResourceConfig<T> {
|
|
326
|
+
/** The first element of every cache key of this resource, e.g. `'invoices'`. */
|
|
327
|
+
name: string
|
|
328
|
+
/** The collection's path under the API base, e.g. `'/invoices'`. */
|
|
329
|
+
path: string
|
|
330
|
+
/** The app's HTTP client, read on every call so a client bonded later is the one used. */
|
|
331
|
+
http: () => ResourceHttp
|
|
332
|
+
/** The field a record is addressed by in a URL. Defaults to `'id'`. */
|
|
333
|
+
id?: keyof T & string
|
|
334
|
+
/** The HTTP method the API updates a record with. Defaults to `'put'`. */
|
|
335
|
+
updateMethod?: 'put' | 'patch'
|
|
336
|
+
/** Reads the records out of a list response. Defaults to the body itself. */
|
|
337
|
+
readList?: (response: ResourceResponse) => T[]
|
|
338
|
+
/** Reads the record out of a detail or write response. Defaults to the body itself. */
|
|
339
|
+
readOne?: (response: ResourceResponse) => T | null
|
|
340
|
+
}
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
#### `QueryResource`
|
|
344
|
+
|
|
345
|
+
The reads and writes {@link createQueryResource} returns.
|
|
346
|
+
|
|
347
|
+
```typescript
|
|
348
|
+
interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
|
|
349
|
+
/**
|
|
350
|
+
* `useQuery` options for the collection. `viewer` is who the answer is for (the signed-in id,
|
|
351
|
+
* or `'anonymous'`); a page or filter change keeps the rows on screen until the next answer.
|
|
352
|
+
*/
|
|
353
|
+
list(viewer: string, params?: Record<string, unknown>): QueryOptions<T[]>
|
|
354
|
+
/**
|
|
355
|
+
* `useQuery` options for one record, or null while `id` is not known yet (`useQuery(null)`
|
|
356
|
+
* observes nothing). A missing record resolves to null, not to an error.
|
|
357
|
+
*/
|
|
358
|
+
detail(viewer: string, id: string | null | undefined): QueryOptions<T | null> | null
|
|
359
|
+
/** Creates a record, shows it in the cache and refreshes the lists on screen. */
|
|
360
|
+
create(viewer: string, input: Create): Promise<T>
|
|
361
|
+
/** Updates a record, shows the saved record in the cache and refreshes the lists on screen. */
|
|
362
|
+
update(viewer: string, id: string, input: Update): Promise<T>
|
|
363
|
+
/** Removes a record, drops it from the cache and refreshes the lists on screen. */
|
|
364
|
+
remove(viewer: string, id: string): Promise<void>
|
|
365
|
+
/**
|
|
366
|
+
* Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
|
|
367
|
+
* `DELETE path/id/action` turns it off. Resolves with the saved record, so it is the `commit`
|
|
368
|
+
* of `useOptimisticValue`.
|
|
369
|
+
*/
|
|
370
|
+
toggle(viewer: string, id: string, action: string, on: boolean): Promise<T>
|
|
371
|
+
/** Fetches the lists on screen again, after a change this resource did not make itself. */
|
|
372
|
+
refresh(viewer: string): Promise<void>
|
|
373
|
+
}
|
|
374
|
+
```
|
|
375
|
+
|
|
238
376
|
#### `IntentPrefetchProps`
|
|
239
377
|
|
|
240
378
|
The handlers {@link intentPrefetchProps} returns.
|
|
@@ -249,6 +387,30 @@ interface IntentPrefetchProps {
|
|
|
249
387
|
|
|
250
388
|
### Functions
|
|
251
389
|
|
|
390
|
+
#### `createQueryResource(config)`
|
|
391
|
+
|
|
392
|
+
Describe one API resource once and get its reads and writes on the shared cache.
|
|
393
|
+
|
|
394
|
+
A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
|
|
395
|
+
re-solve the same three problems on every screen: a late answer for the previous page lands
|
|
396
|
+
over the current one, a list still shows what it showed before a comment was added, and a
|
|
397
|
+
button is live before its record exists. Here the reads are `useQuery` options (one key per
|
|
398
|
+
viewer, page and filter; the previous rows stay until the next answer) and every write puts
|
|
399
|
+
the server's own record into the cache and fetches the lists on screen again.
|
|
400
|
+
|
|
401
|
+
Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
|
|
402
|
+
and the query provider are whatever the app bonded.
|
|
403
|
+
|
|
404
|
+
```typescript
|
|
405
|
+
function createQueryResource<T, Create = Partial<T>, Update = Partial<T>>(
|
|
406
|
+
config: QueryResourceConfig<T>,
|
|
407
|
+
): QueryResource<T, Create, Update>
|
|
408
|
+
```
|
|
409
|
+
|
|
410
|
+
- `config` — The resource's name, path, HTTP client and response readers.
|
|
411
|
+
|
|
412
|
+
**Returns:** List and detail query options, and create, update, remove, toggle and refresh.
|
|
413
|
+
|
|
252
414
|
#### `prefetchQuery(options)`
|
|
253
415
|
|
|
254
416
|
Warms the cache for a document, when the connection can afford it (see
|
package/dist/index.d.ts
CHANGED
|
@@ -195,6 +195,55 @@
|
|
|
195
195
|
* }
|
|
196
196
|
* ```
|
|
197
197
|
*
|
|
198
|
+
* @example
|
|
199
|
+
* One API resource described once, for every page that reads or changes it.
|
|
200
|
+
* `createQueryResource` returns the list and detail reads as `useQuery` options and the writes
|
|
201
|
+
* as functions that put the server's record into the cache and fetch the lists on screen again,
|
|
202
|
+
* so a page never mirrors a response into `useState`. A flag the API models as a sub-path
|
|
203
|
+
* (`POST /invoices/:id/flag`, `DELETE` to clear it) is `toggle`, which resolves with the saved
|
|
204
|
+
* record and is the `commit` of `useOptimisticValue`.
|
|
205
|
+
*
|
|
206
|
+
* ```tsx
|
|
207
|
+
* import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
|
|
208
|
+
* import { createQueryResource, useQuery } from '@molecule/app-query-react'
|
|
209
|
+
* import { useAuth, useOptimisticValue } from '@molecule/app-react'
|
|
210
|
+
*
|
|
211
|
+
* interface Invoice {
|
|
212
|
+
* id: string
|
|
213
|
+
* number: string
|
|
214
|
+
* flagged: boolean
|
|
215
|
+
* }
|
|
216
|
+
*
|
|
217
|
+
* export const invoices = createQueryResource<Invoice>({
|
|
218
|
+
* name: 'invoices',
|
|
219
|
+
* path: '/invoices',
|
|
220
|
+
* http: getClient,
|
|
221
|
+
* readList: (response) => unwrapList<Invoice>(response),
|
|
222
|
+
* readOne: (response) => unwrapSingle<Invoice>(response),
|
|
223
|
+
* })
|
|
224
|
+
*
|
|
225
|
+
* function InvoicePage({ id }: { id: string }) {
|
|
226
|
+
* const { user } = useAuth<{ id: string }>()
|
|
227
|
+
* const viewer = user ? String(user.id) : 'anonymous'
|
|
228
|
+
* const { data: invoice, status } = useQuery(invoices.detail(viewer, id))
|
|
229
|
+
* if (status === 'idle' || status === 'loading') return <p role=status>…</p>
|
|
230
|
+
* if (!invoice) return <p role=alert>…</p>
|
|
231
|
+
* return <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />
|
|
232
|
+
* }
|
|
233
|
+
*
|
|
234
|
+
* function FlagButton({ invoice, viewer }: { invoice: Invoice; viewer: string }) {
|
|
235
|
+
* const flag = useOptimisticValue({
|
|
236
|
+
* value: invoice.flagged,
|
|
237
|
+
* commit: async (on) => (await invoices.toggle(viewer, invoice.id, 'flag', on)).flagged,
|
|
238
|
+
* })
|
|
239
|
+
* return (
|
|
240
|
+
* <button type=button aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
|
|
241
|
+
* {invoice.number}
|
|
242
|
+
* </button>
|
|
243
|
+
* )
|
|
244
|
+
* }
|
|
245
|
+
* ```
|
|
246
|
+
*
|
|
198
247
|
* @remarks
|
|
199
248
|
* - **`useQuery` reads the cache synchronously on the first render.** A
|
|
200
249
|
* document prefetched from a hovered link, or seeded with `client.set()`
|
|
@@ -261,6 +310,7 @@
|
|
|
261
310
|
*
|
|
262
311
|
* @module
|
|
263
312
|
*/
|
|
313
|
+
export * from './resource.js';
|
|
264
314
|
export * from './usePrefetch.js';
|
|
265
315
|
export * from './useQuery.js';
|
|
266
316
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuTG;AAEH,cAAc,eAAe,CAAA;AAC7B,cAAc,kBAAkB,CAAA;AAChC,cAAc,eAAe,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -195,6 +195,55 @@
|
|
|
195
195
|
* }
|
|
196
196
|
* ```
|
|
197
197
|
*
|
|
198
|
+
* @example
|
|
199
|
+
* One API resource described once, for every page that reads or changes it.
|
|
200
|
+
* `createQueryResource` returns the list and detail reads as `useQuery` options and the writes
|
|
201
|
+
* as functions that put the server's record into the cache and fetch the lists on screen again,
|
|
202
|
+
* so a page never mirrors a response into `useState`. A flag the API models as a sub-path
|
|
203
|
+
* (`POST /invoices/:id/flag`, `DELETE` to clear it) is `toggle`, which resolves with the saved
|
|
204
|
+
* record and is the `commit` of `useOptimisticValue`.
|
|
205
|
+
*
|
|
206
|
+
* ```tsx
|
|
207
|
+
* import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
|
|
208
|
+
* import { createQueryResource, useQuery } from '@molecule/app-query-react'
|
|
209
|
+
* import { useAuth, useOptimisticValue } from '@molecule/app-react'
|
|
210
|
+
*
|
|
211
|
+
* interface Invoice {
|
|
212
|
+
* id: string
|
|
213
|
+
* number: string
|
|
214
|
+
* flagged: boolean
|
|
215
|
+
* }
|
|
216
|
+
*
|
|
217
|
+
* export const invoices = createQueryResource<Invoice>({
|
|
218
|
+
* name: 'invoices',
|
|
219
|
+
* path: '/invoices',
|
|
220
|
+
* http: getClient,
|
|
221
|
+
* readList: (response) => unwrapList<Invoice>(response),
|
|
222
|
+
* readOne: (response) => unwrapSingle<Invoice>(response),
|
|
223
|
+
* })
|
|
224
|
+
*
|
|
225
|
+
* function InvoicePage({ id }: { id: string }) {
|
|
226
|
+
* const { user } = useAuth<{ id: string }>()
|
|
227
|
+
* const viewer = user ? String(user.id) : 'anonymous'
|
|
228
|
+
* const { data: invoice, status } = useQuery(invoices.detail(viewer, id))
|
|
229
|
+
* if (status === 'idle' || status === 'loading') return <p role=status>…</p>
|
|
230
|
+
* if (!invoice) return <p role=alert>…</p>
|
|
231
|
+
* return <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />
|
|
232
|
+
* }
|
|
233
|
+
*
|
|
234
|
+
* function FlagButton({ invoice, viewer }: { invoice: Invoice; viewer: string }) {
|
|
235
|
+
* const flag = useOptimisticValue({
|
|
236
|
+
* value: invoice.flagged,
|
|
237
|
+
* commit: async (on) => (await invoices.toggle(viewer, invoice.id, 'flag', on)).flagged,
|
|
238
|
+
* })
|
|
239
|
+
* return (
|
|
240
|
+
* <button type=button aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
|
|
241
|
+
* {invoice.number}
|
|
242
|
+
* </button>
|
|
243
|
+
* )
|
|
244
|
+
* }
|
|
245
|
+
* ```
|
|
246
|
+
*
|
|
198
247
|
* @remarks
|
|
199
248
|
* - **`useQuery` reads the cache synchronously on the first render.** A
|
|
200
249
|
* document prefetched from a hovered link, or seeded with `client.set()`
|
|
@@ -261,5 +310,6 @@
|
|
|
261
310
|
*
|
|
262
311
|
* @module
|
|
263
312
|
*/
|
|
313
|
+
export * from './resource.js';
|
|
264
314
|
export * from './usePrefetch.js';
|
|
265
315
|
export * from './useQuery.js';
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One API resource on the shared query cache: its list and detail reads as `useQuery` options,
|
|
3
|
+
* and its writes as functions that put the server's answer into the cache.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import type { QueryOptions } from '@molecule/app-query';
|
|
8
|
+
/** The part of an HTTP response a resource reads. */
|
|
9
|
+
export interface ResourceResponse {
|
|
10
|
+
/** The parsed response body. */
|
|
11
|
+
data: unknown;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The HTTP client a resource calls: the app's own bonded client (`getClient()` from
|
|
15
|
+
* `@molecule/app-http`) has this shape. Only what a resource uses is named here.
|
|
16
|
+
*/
|
|
17
|
+
export interface ResourceHttp {
|
|
18
|
+
/** Reads `path`; `signal` cancels it and `params` become the query string. */
|
|
19
|
+
get(path: string, options?: {
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
params?: Record<string, unknown>;
|
|
22
|
+
}): Promise<ResourceResponse>;
|
|
23
|
+
/** Creates at `path`. */
|
|
24
|
+
post(path: string, body?: unknown): Promise<ResourceResponse>;
|
|
25
|
+
/** Replaces at `path`. */
|
|
26
|
+
put(path: string, body?: unknown): Promise<ResourceResponse>;
|
|
27
|
+
/** Changes part of the record at `path`. */
|
|
28
|
+
patch(path: string, body?: unknown): Promise<ResourceResponse>;
|
|
29
|
+
/** Removes at `path`. */
|
|
30
|
+
delete(path: string): Promise<ResourceResponse>;
|
|
31
|
+
}
|
|
32
|
+
/** What {@link createQueryResource} needs to know about one resource. */
|
|
33
|
+
export interface QueryResourceConfig<T> {
|
|
34
|
+
/** The first element of every cache key of this resource, e.g. `'invoices'`. */
|
|
35
|
+
name: string;
|
|
36
|
+
/** The collection's path under the API base, e.g. `'/invoices'`. */
|
|
37
|
+
path: string;
|
|
38
|
+
/** The app's HTTP client, read on every call so a client bonded later is the one used. */
|
|
39
|
+
http: () => ResourceHttp;
|
|
40
|
+
/** The field a record is addressed by in a URL. Defaults to `'id'`. */
|
|
41
|
+
id?: keyof T & string;
|
|
42
|
+
/** The HTTP method the API updates a record with. Defaults to `'put'`. */
|
|
43
|
+
updateMethod?: 'put' | 'patch';
|
|
44
|
+
/** Reads the records out of a list response. Defaults to the body itself. */
|
|
45
|
+
readList?: (response: ResourceResponse) => T[];
|
|
46
|
+
/** Reads the record out of a detail or write response. Defaults to the body itself. */
|
|
47
|
+
readOne?: (response: ResourceResponse) => T | null;
|
|
48
|
+
}
|
|
49
|
+
/** The reads and writes {@link createQueryResource} returns. */
|
|
50
|
+
export interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
|
|
51
|
+
/**
|
|
52
|
+
* `useQuery` options for the collection. `viewer` is who the answer is for (the signed-in id,
|
|
53
|
+
* or `'anonymous'`); a page or filter change keeps the rows on screen until the next answer.
|
|
54
|
+
*/
|
|
55
|
+
list(viewer: string, params?: Record<string, unknown>): QueryOptions<T[]>;
|
|
56
|
+
/**
|
|
57
|
+
* `useQuery` options for one record, or null while `id` is not known yet (`useQuery(null)`
|
|
58
|
+
* observes nothing). A missing record resolves to null, not to an error.
|
|
59
|
+
*/
|
|
60
|
+
detail(viewer: string, id: string | null | undefined): QueryOptions<T | null> | null;
|
|
61
|
+
/** Creates a record, shows it in the cache and refreshes the lists on screen. */
|
|
62
|
+
create(viewer: string, input: Create): Promise<T>;
|
|
63
|
+
/** Updates a record, shows the saved record in the cache and refreshes the lists on screen. */
|
|
64
|
+
update(viewer: string, id: string, input: Update): Promise<T>;
|
|
65
|
+
/** Removes a record, drops it from the cache and refreshes the lists on screen. */
|
|
66
|
+
remove(viewer: string, id: string): Promise<void>;
|
|
67
|
+
/**
|
|
68
|
+
* Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
|
|
69
|
+
* `DELETE path/id/action` turns it off. Resolves with the saved record, so it is the `commit`
|
|
70
|
+
* of `useOptimisticValue`.
|
|
71
|
+
*/
|
|
72
|
+
toggle(viewer: string, id: string, action: string, on: boolean): Promise<T>;
|
|
73
|
+
/** Fetches the lists on screen again, after a change this resource did not make itself. */
|
|
74
|
+
refresh(viewer: string): Promise<void>;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Describe one API resource once and get its reads and writes on the shared cache.
|
|
78
|
+
*
|
|
79
|
+
* A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
|
|
80
|
+
* re-solve the same three problems on every screen: a late answer for the previous page lands
|
|
81
|
+
* over the current one, a list still shows what it showed before a comment was added, and a
|
|
82
|
+
* button is live before its record exists. Here the reads are `useQuery` options (one key per
|
|
83
|
+
* viewer, page and filter; the previous rows stay until the next answer) and every write puts
|
|
84
|
+
* the server's own record into the cache and fetches the lists on screen again.
|
|
85
|
+
*
|
|
86
|
+
* Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
|
|
87
|
+
* and the query provider are whatever the app bonded.
|
|
88
|
+
*
|
|
89
|
+
* @param config - The resource's name, path, HTTP client and response readers.
|
|
90
|
+
* @returns List and detail query options, and create, update, remove, toggle and refresh.
|
|
91
|
+
* @throws {Error} When a write's response holds no record.
|
|
92
|
+
*/
|
|
93
|
+
export declare function createQueryResource<T, Create = Partial<T>, Update = Partial<T>>(config: QueryResourceConfig<T>): QueryResource<T, Create, Update>;
|
|
94
|
+
//# sourceMappingURL=resource.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../src/resource.ts"],"names":[],"mappings":"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"}
|
package/dist/resource.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One API resource on the shared query cache: its list and detail reads as `useQuery` options,
|
|
3
|
+
* and its writes as functions that put the server's answer into the cache.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import { getQueryClient, hashQueryKey } from '@molecule/app-query';
|
|
8
|
+
/** How many of a viewer's most recent lists a write fetches again. */
|
|
9
|
+
const REFRESHED_LISTS = 4;
|
|
10
|
+
/**
|
|
11
|
+
* Describe one API resource once and get its reads and writes on the shared cache.
|
|
12
|
+
*
|
|
13
|
+
* A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
|
|
14
|
+
* re-solve the same three problems on every screen: a late answer for the previous page lands
|
|
15
|
+
* over the current one, a list still shows what it showed before a comment was added, and a
|
|
16
|
+
* button is live before its record exists. Here the reads are `useQuery` options (one key per
|
|
17
|
+
* viewer, page and filter; the previous rows stay until the next answer) and every write puts
|
|
18
|
+
* the server's own record into the cache and fetches the lists on screen again.
|
|
19
|
+
*
|
|
20
|
+
* Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
|
|
21
|
+
* and the query provider are whatever the app bonded.
|
|
22
|
+
*
|
|
23
|
+
* @param config - The resource's name, path, HTTP client and response readers.
|
|
24
|
+
* @returns List and detail query options, and create, update, remove, toggle and refresh.
|
|
25
|
+
* @throws {Error} When a write's response holds no record.
|
|
26
|
+
*/
|
|
27
|
+
export function createQueryResource(config) {
|
|
28
|
+
const readList = config.readList ?? ((response) => response.data);
|
|
29
|
+
const readOne = config.readOne ?? ((response) => response.data);
|
|
30
|
+
const idField = config.id ?? 'id';
|
|
31
|
+
const base = config.path.replace(/\/+$/, '');
|
|
32
|
+
const one = (id) => `${base}/${encodeURIComponent(id)}`;
|
|
33
|
+
const detailKey = (viewer, id) => [config.name, viewer, 'detail', id];
|
|
34
|
+
// The lists handed out most recently, newest last: the ones a write fetches again. A list
|
|
35
|
+
// nobody reads any more costs one request and is then dropped by the next ones.
|
|
36
|
+
const recent = new Map();
|
|
37
|
+
const list = (viewer, params = {}) => {
|
|
38
|
+
const options = {
|
|
39
|
+
key: [config.name, viewer, 'list', params],
|
|
40
|
+
principal: viewer,
|
|
41
|
+
keepPreviousData: true,
|
|
42
|
+
fetch: async (signal) => readList(await config.http().get(base, { signal, params })),
|
|
43
|
+
};
|
|
44
|
+
const hash = hashQueryKey(options.key);
|
|
45
|
+
recent.delete(hash);
|
|
46
|
+
recent.set(hash, { viewer, options });
|
|
47
|
+
for (const stale of [...recent.keys()].slice(0, -REFRESHED_LISTS))
|
|
48
|
+
recent.delete(stale);
|
|
49
|
+
return options;
|
|
50
|
+
};
|
|
51
|
+
const refresh = async (viewer) => {
|
|
52
|
+
const client = getQueryClient();
|
|
53
|
+
client.invalidate([config.name, viewer, 'list']);
|
|
54
|
+
await Promise.all([...recent.values()]
|
|
55
|
+
.filter((entry) => entry.viewer === viewer)
|
|
56
|
+
.map((entry) => client.fetch(entry.options).catch((_error) => {
|
|
57
|
+
// The mounted `useQuery` of that list presents its own failure as `status: 'error'`;
|
|
58
|
+
// the write that asked for this refresh succeeded and must not reject over it.
|
|
59
|
+
})));
|
|
60
|
+
};
|
|
61
|
+
const saved = async (viewer, response) => {
|
|
62
|
+
const record = readOne(response);
|
|
63
|
+
if (record == null)
|
|
64
|
+
throw new Error(`${config.name}: the response held no record`);
|
|
65
|
+
const id = record[idField];
|
|
66
|
+
if (typeof id === 'string' || typeof id === 'number')
|
|
67
|
+
getQueryClient().set(detailKey(viewer, String(id)), record);
|
|
68
|
+
await refresh(viewer);
|
|
69
|
+
return record;
|
|
70
|
+
};
|
|
71
|
+
return {
|
|
72
|
+
list,
|
|
73
|
+
detail: (viewer, id) => id == null || id === ''
|
|
74
|
+
? null
|
|
75
|
+
: {
|
|
76
|
+
key: detailKey(viewer, id),
|
|
77
|
+
principal: viewer,
|
|
78
|
+
fetch: async (signal) => {
|
|
79
|
+
try {
|
|
80
|
+
return readOne(await config.http().get(one(id), { signal }));
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
// A record that does not exist is an answer, not a failed load.
|
|
84
|
+
if (error?.status === 404)
|
|
85
|
+
return null;
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
create: async (viewer, input) => saved(viewer, await config.http().post(base, input)),
|
|
91
|
+
update: async (viewer, id, input) => saved(viewer, await config.http()[config.updateMethod ?? 'put'](one(id), input)),
|
|
92
|
+
remove: async (viewer, id) => {
|
|
93
|
+
await config.http().delete(one(id));
|
|
94
|
+
getQueryClient().set(detailKey(viewer, id), null);
|
|
95
|
+
await refresh(viewer);
|
|
96
|
+
},
|
|
97
|
+
toggle: async (viewer, id, action, on) => {
|
|
98
|
+
const path = `${one(id)}/${action.replace(/^\/+/, '')}`;
|
|
99
|
+
return saved(viewer, on ? await config.http().post(path) : await config.http().delete(path));
|
|
100
|
+
},
|
|
101
|
+
refresh,
|
|
102
|
+
};
|
|
103
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@molecule/app-query-react",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "React hooks for @molecule/app-query — read a cached document synchronously, observe it, and prefetch on intent",
|
|
5
5
|
"homepage": "https://www.molecule.dev/packages/app-query-react",
|
|
6
6
|
"type": "module",
|