@molecule/app-query-react 1.1.6 → 1.3.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 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-09T15:00:50.006Z
6
+ Generated: 2026-11-12T06:19:59.085Z
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,111 @@ 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
+
376
+ #### `UseQueryResult`
377
+
378
+ A mounted query's state and its explicit refresh action.
379
+
380
+ ```typescript
381
+ interface UseQueryResult<T> extends QueryState<T> {
382
+ /**
383
+ * Fetch this key again, even when its cached document is fresh. Observers receive the
384
+ * updated state. Resolves with that state, including an error when the request fails;
385
+ * a disabled (`null`) query resolves idle without a request.
386
+ */
387
+ refetch: () => Promise<QueryState<T>>
388
+ }
389
+ ```
390
+
238
391
  #### `IntentPrefetchProps`
239
392
 
240
393
  The handlers {@link intentPrefetchProps} returns.
@@ -249,6 +402,30 @@ interface IntentPrefetchProps {
249
402
 
250
403
  ### Functions
251
404
 
405
+ #### `createQueryResource(config)`
406
+
407
+ Describe one API resource once and get its reads and writes on the shared cache.
408
+
409
+ A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
410
+ re-solve the same three problems on every screen: a late answer for the previous page lands
411
+ over the current one, a list still shows what it showed before a comment was added, and a
412
+ button is live before its record exists. Here the reads are `useQuery` options (one key per
413
+ viewer, page and filter; the previous rows stay until the next answer) and every write puts
414
+ the server's own record into the cache and fetches the lists on screen again.
415
+
416
+ Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
417
+ and the query provider are whatever the app bonded.
418
+
419
+ ```typescript
420
+ function createQueryResource<T, Create = Partial<T>, Update = Partial<T>>(
421
+ config: QueryResourceConfig<T>,
422
+ ): QueryResource<T, Create, Update>
423
+ ```
424
+
425
+ - `config` — The resource's name, path, HTTP client and response readers.
426
+
427
+ **Returns:** List and detail query options, and create, update, remove, toggle and refresh.
428
+
252
429
  #### `prefetchQuery(options)`
253
430
 
254
431
  Warms the cache for a document, when the connection can afford it (see
@@ -302,6 +479,8 @@ lands. It is aborted only when the key changes or the component unmounts
302
479
  `useEffect` + `fetch`: an effect whose cleanup sets a `cancelled` flag, and
303
480
  whose deps include a function rebuilt each render, cancels its own request
304
481
  on every re-render and then skips the refetch.
482
+ An explicit `refetch()` is an awaited cache fetch; it can finish after the observer unmounts,
483
+ like an explicit `client.fetch(options)` caller.
305
484
 
306
485
  For a LIST, put the route's page, filter and selected view in the key and
307
486
  pass `keepPreviousData` with a `principal`: a Next/Previous or filter change
@@ -315,12 +494,12 @@ an endpoint that answers every viewer the same takes a viewer-free key with
315
494
  `principal: 'public'`.
316
495
 
317
496
  ```typescript
318
- function useQuery<T>(options: QueryOptions<T> | null): QueryState<T>
497
+ function useQuery<T>(options: QueryOptions<T> | null): UseQueryResult<T>
319
498
  ```
320
499
 
321
500
  - `options` — Key, fetch, freshness, and optionally `principal` with `keepPreviousData`; or `null`.
322
501
 
323
- **Returns:** The document's state. `isPreviousData` is `true` while `data` is the previous key's document for the same principal.
502
+ **Returns:** The document's state and `refetch()`. `isPreviousData` is `true` while `data` is the previous key's document for the same principal.
324
503
 
325
504
  ## Injection Notes
326
505
 
@@ -386,6 +565,11 @@ Peer dependencies:
386
565
  - Prefetching respects the browser's data-saver setting and skips 2G
387
566
  connections (`shouldPrefetch()` in the core) — do not bypass that for
388
567
  "important" links; the person can still click.
568
+ - **Refresh a mounted document with `query.refetch()`.** It fetches even a fresh cache
569
+ entry and updates every observer of that key. After a mutation whose response is not the
570
+ whole document, `await query.refetch()` reloads the displayed list. It resolves with the
571
+ resulting state (including `status: 'error'` on failure); a disabled query stays idle.
572
+ Prefer `client.set(key, response)` when the mutation already returned the whole document.
389
573
  - Errors are not thrown from the hook; read `status === 'error'` and
390
574
  `error`. `client.invalidate()` does NOT refetch a mounted page — it only
391
575
  marks documents stale, so the page keeps its error (or its old document)
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()`
@@ -246,6 +295,11 @@
246
295
  * - Prefetching respects the browser's data-saver setting and skips 2G
247
296
  * connections (`shouldPrefetch()` in the core) — do not bypass that for
248
297
  * "important" links; the person can still click.
298
+ * - **Refresh a mounted document with `query.refetch()`.** It fetches even a fresh cache
299
+ * entry and updates every observer of that key. After a mutation whose response is not the
300
+ * whole document, `await query.refetch()` reloads the displayed list. It resolves with the
301
+ * resulting state (including `status: 'error'` on failure); a disabled query stays idle.
302
+ * Prefer `client.set(key, response)` when the mutation already returned the whole document.
249
303
  * - Errors are not thrown from the hook; read `status === 'error'` and
250
304
  * `error`. `client.invalidate()` does NOT refetch a mounted page — it only
251
305
  * marks documents stale, so the page keeps its error (or its old document)
@@ -261,6 +315,8 @@
261
315
  *
262
316
  * @module
263
317
  */
318
+ export * from './resource.js';
319
+ export * from './types.js';
264
320
  export * from './usePrefetch.js';
265
321
  export * from './useQuery.js';
266
322
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsQG;AAEH,cAAc,kBAAkB,CAAA;AAChC,cAAc,eAAe,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4TG;AAEH,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA;AAC1B,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()`
@@ -246,6 +295,11 @@
246
295
  * - Prefetching respects the browser's data-saver setting and skips 2G
247
296
  * connections (`shouldPrefetch()` in the core) — do not bypass that for
248
297
  * "important" links; the person can still click.
298
+ * - **Refresh a mounted document with `query.refetch()`.** It fetches even a fresh cache
299
+ * entry and updates every observer of that key. After a mutation whose response is not the
300
+ * whole document, `await query.refetch()` reloads the displayed list. It resolves with the
301
+ * resulting state (including `status: 'error'` on failure); a disabled query stays idle.
302
+ * Prefer `client.set(key, response)` when the mutation already returned the whole document.
249
303
  * - Errors are not thrown from the hook; read `status === 'error'` and
250
304
  * `error`. `client.invalidate()` does NOT refetch a mounted page — it only
251
305
  * marks documents stale, so the page keeps its error (or its old document)
@@ -261,5 +315,7 @@
261
315
  *
262
316
  * @module
263
317
  */
318
+ export * from './resource.js';
319
+ export * from './types.js';
264
320
  export * from './usePrefetch.js';
265
321
  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":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAY,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAGjE,qDAAqD;AACrD,MAAM,WAAW,gBAAgB;IAC/B,gCAAgC;IAChC,IAAI,EAAE,OAAO,CAAA;CACd;AAED;;;GAGG;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,CAAC,CAAC,GAC7B,aAAa,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,CAkFlC"}
@@ -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
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * React query observer contracts.
3
+ * @module
4
+ */
5
+ import type { QueryState } from '@molecule/app-query';
6
+ /** A mounted query's state and its explicit refresh action. */
7
+ export interface UseQueryResult<T> extends QueryState<T> {
8
+ /**
9
+ * Fetch this key again, even when its cached document is fresh. Observers receive the
10
+ * updated state. Resolves with that state, including an error when the request fails;
11
+ * a disabled (`null`) query resolves idle without a request.
12
+ */
13
+ refetch: () => Promise<QueryState<T>>;
14
+ }
15
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAErD,+DAA+D;AAC/D,MAAM,WAAW,cAAc,CAAC,CAAC,CAAE,SAAQ,UAAU,CAAC,CAAC,CAAC;IACtD;;;;OAIG;IACH,OAAO,EAAE,MAAM,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAA;CACtC"}
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * @module
5
5
  */
6
- import type { QueryOptions, QueryState } from '@molecule/app-query';
6
+ import type { QueryOptions } from '@molecule/app-query';
7
+ import type { UseQueryResult } from './types.js';
7
8
  /**
8
9
  * The document for `options.key`, kept current: cached data is returned on
9
10
  * the very first render (so a warmed page never flashes a loading state),
@@ -20,6 +21,8 @@ import type { QueryOptions, QueryState } from '@molecule/app-query';
20
21
  * `useEffect` + `fetch`: an effect whose cleanup sets a `cancelled` flag, and
21
22
  * whose deps include a function rebuilt each render, cancels its own request
22
23
  * on every re-render and then skips the refetch.
24
+ * An explicit `refetch()` is an awaited cache fetch; it can finish after the observer unmounts,
25
+ * like an explicit `client.fetch(options)` caller.
23
26
  *
24
27
  * For a LIST, put the route's page, filter and selected view in the key and
25
28
  * pass `keepPreviousData` with a `principal`: a Next/Previous or filter change
@@ -34,11 +37,11 @@ import type { QueryOptions, QueryState } from '@molecule/app-query';
34
37
  *
35
38
  * @param options - Key, fetch, freshness, and optionally `principal` with
36
39
  * `keepPreviousData`; or `null`.
37
- * @returns The document's state. `isPreviousData` is `true` while `data` is
40
+ * @returns The document's state and `refetch()`. `isPreviousData` is `true` while `data` is
38
41
  * the previous key's document for the same principal.
39
42
  * @throws {Error} When `keepPreviousData` is set without `principal` — the
40
43
  * hook cannot tell a route change from a principal switch, so it refuses
41
44
  * rather than risk showing one principal's document to another.
42
45
  */
43
- export declare function useQuery<T>(options: QueryOptions<T> | null): QueryState<T>;
46
+ export declare function useQuery<T>(options: QueryOptions<T> | null): UseQueryResult<T>;
44
47
  //# sourceMappingURL=useQuery.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"useQuery.d.ts","sourceRoot":"","sources":["../src/useQuery.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAwBnE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,UAAU,CAAC,CAAC,CAAC,CA0E1E"}
1
+ {"version":3,"file":"useQuery.d.ts","sourceRoot":"","sources":["../src/useQuery.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAc,MAAM,qBAAqB,CAAA;AAGnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAuBhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,cAAc,CAAC,CAAC,CAAC,CAsF9E"}
package/dist/useQuery.js CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * @module
5
5
  */
6
- import { useEffect, useMemo, useRef, useState } from 'react';
6
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
7
7
  import { getQueryClient, hashQueryKey } from '@molecule/app-query';
8
8
  const IDLE = {
9
9
  data: undefined,
@@ -28,6 +28,8 @@ const IDLE = {
28
28
  * `useEffect` + `fetch`: an effect whose cleanup sets a `cancelled` flag, and
29
29
  * whose deps include a function rebuilt each render, cancels its own request
30
30
  * on every re-render and then skips the refetch.
31
+ * An explicit `refetch()` is an awaited cache fetch; it can finish after the observer unmounts,
32
+ * like an explicit `client.fetch(options)` caller.
31
33
  *
32
34
  * For a LIST, put the route's page, filter and selected view in the key and
33
35
  * pass `keepPreviousData` with a `principal`: a Next/Previous or filter change
@@ -42,7 +44,7 @@ const IDLE = {
42
44
  *
43
45
  * @param options - Key, fetch, freshness, and optionally `principal` with
44
46
  * `keepPreviousData`; or `null`.
45
- * @returns The document's state. `isPreviousData` is `true` while `data` is
47
+ * @returns The document's state and `refetch()`. `isPreviousData` is `true` while `data` is
46
48
  * the previous key's document for the same principal.
47
49
  * @throws {Error} When `keepPreviousData` is set without `principal` — the
48
50
  * hook cannot tell a route change from a principal switch, so it refuses
@@ -58,6 +60,20 @@ export function useQuery(options) {
58
60
  // Options are read once per key: a fresh `fetch` closure every render must
59
61
  // not resubscribe.
60
62
  const stable = useMemo(() => options, [hash]);
63
+ const refetch = useCallback(async () => {
64
+ if (!stable)
65
+ return IDLE;
66
+ const client = getQueryClient();
67
+ client.invalidate(stable.key);
68
+ try {
69
+ await client.fetch(stable);
70
+ }
71
+ catch (_error) {
72
+ // The cache publishes the failure to every observer. Return that state just as the
73
+ // initial subscription does, so an event handler can safely use `void query.refetch()`.
74
+ }
75
+ return client.getState(stable.key);
76
+ }, [stable]);
61
77
  const [state, setState] = useState(() => ({
62
78
  hash,
63
79
  value: stable ? getQueryClient().getState(stable.key) : IDLE,
@@ -114,5 +130,5 @@ export function useQuery(options) {
114
130
  const client = getQueryClient();
115
131
  return client.subscribe(stable, (value) => setState({ hash, value }));
116
132
  }, [stable, hash]);
117
- return value;
133
+ return useMemo(() => ({ ...value, refetch }), [value, refetch]);
118
134
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/app-query-react",
3
- "version": "1.1.6",
3
+ "version": "1.3.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",