@molecule/app-query-react 1.6.0 → 1.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +73 -34
- package/dist/index.d.ts +19 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +19 -8
- package/dist/resource.d.ts +5 -97
- package/dist/resource.d.ts.map +1 -1
- package/dist/resource.js +4 -156
- package/dist/usePrefetch.d.ts +3 -9
- package/dist/usePrefetch.d.ts.map +1 -1
- package/dist/usePrefetch.js +4 -14
- package/dist/useQuery.d.ts +5 -0
- package/dist/useQuery.d.ts.map +1 -1
- package/dist/useQuery.js +5 -0
- package/package.json +3 -3
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-14T12:29:21.947Z
|
|
7
7
|
-->
|
|
8
8
|
|
|
9
9
|
# @molecule/app-query-react
|
|
@@ -236,8 +236,8 @@ record and is the `commit` of `useOptimisticValue`.
|
|
|
236
236
|
|
|
237
237
|
```tsx
|
|
238
238
|
import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
|
|
239
|
-
import { createQueryResource, useQuery } from '@molecule/app-query-react'
|
|
240
|
-
import { useAuth, useOptimisticValue } from '@molecule/app-react'
|
|
239
|
+
import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-react'
|
|
240
|
+
import { useAuth, useOptimisticValue, useTranslation } from '@molecule/app-react'
|
|
241
241
|
|
|
242
242
|
interface Invoice {
|
|
243
243
|
id: string
|
|
@@ -255,20 +255,40 @@ export const invoices = createQueryResource<Invoice>({
|
|
|
255
255
|
|
|
256
256
|
function InvoicePage({ id }: { id: string }) {
|
|
257
257
|
const { user } = useAuth<{ id: string }>()
|
|
258
|
+
const { t } = useTranslation()
|
|
258
259
|
const viewer = user ? String(user.id) : 'anonymous'
|
|
259
|
-
const
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
260
|
+
const query = useQuery(invoices.detail(viewer, id))
|
|
261
|
+
return (
|
|
262
|
+
<QueryContent
|
|
263
|
+
query={query}
|
|
264
|
+
pending={<p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>}
|
|
265
|
+
missing={
|
|
266
|
+
<p role="alert">
|
|
267
|
+
{t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' })}
|
|
268
|
+
</p>
|
|
269
|
+
}
|
|
270
|
+
error={() => (
|
|
271
|
+
<p role="alert">
|
|
272
|
+
{t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' })}
|
|
273
|
+
</p>
|
|
274
|
+
)}
|
|
275
|
+
>
|
|
276
|
+
{(invoice) => <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />}
|
|
277
|
+
</QueryContent>
|
|
278
|
+
)
|
|
263
279
|
}
|
|
264
280
|
|
|
265
281
|
function FlagButton({ invoice, viewer }: { invoice: Invoice; viewer: string }) {
|
|
282
|
+
const { t } = useTranslation()
|
|
266
283
|
const flag = useOptimisticValue({
|
|
267
284
|
value: invoice.flagged,
|
|
268
285
|
commit: async (on) => (await invoices.toggle(viewer, invoice.id, 'flag', on)).flagged,
|
|
269
286
|
})
|
|
270
287
|
return (
|
|
271
|
-
<button type=button aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
|
|
288
|
+
<button type="button" aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
|
|
289
|
+
{flag.value
|
|
290
|
+
? t('invoice.unflag', undefined, { defaultValue: 'Unflag' })
|
|
291
|
+
: t('invoice.flag', undefined, { defaultValue: 'Flag' })}{' '}
|
|
272
292
|
{invoice.number}
|
|
273
293
|
</button>
|
|
274
294
|
)
|
|
@@ -428,6 +448,9 @@ interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
|
|
|
428
448
|
* Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
|
|
429
449
|
* `DELETE path/id/action` turns it off. Resolves with the saved record, so it is the `commit`
|
|
430
450
|
* of `useOptimisticValue`.
|
|
451
|
+
* The saved detail is published before tracked lists finish refreshing; this promise waits
|
|
452
|
+
* for those refreshes. Render the shared controller's value and let it queue inverse clicks
|
|
453
|
+
* during that interval. A page-local busy guard can drop a click on the newly changed label.
|
|
431
454
|
*/
|
|
432
455
|
toggle(viewer: string, id: string, action: string, on: boolean): Promise<T>
|
|
433
456
|
/** Fetches the lists on screen again, after a change this resource did not make itself. */
|
|
@@ -493,39 +516,40 @@ interface IntentPrefetchProps {
|
|
|
493
516
|
|
|
494
517
|
### Functions
|
|
495
518
|
|
|
496
|
-
#### `
|
|
519
|
+
#### `prefetchQuery(options)`
|
|
497
520
|
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
belong outside the list or record container rendered by `children`, and so does a refresh
|
|
502
|
-
line; the default fallbacks render nothing.
|
|
521
|
+
Warms the cache for a document, when the connection can afford it (see
|
|
522
|
+
`shouldPrefetch()` in the core). Safe to call repeatedly: a fresh or
|
|
523
|
+
in-flight document is skipped, and failures are swallowed.
|
|
503
524
|
|
|
504
525
|
```typescript
|
|
505
|
-
function
|
|
506
|
-
query,
|
|
507
|
-
children,
|
|
508
|
-
pending = null,
|
|
509
|
-
missing = null,
|
|
510
|
-
error,
|
|
511
|
-
}: QueryContentProps<T>): ReactNode
|
|
526
|
+
function prefetchQuery<T>(options: QueryOptions<T>): void
|
|
512
527
|
```
|
|
513
528
|
|
|
514
|
-
- `
|
|
515
|
-
|
|
516
|
-
**Returns:** Loaded content or the appropriate fallback.
|
|
529
|
+
- `options` — Key, fetch, freshness.
|
|
517
530
|
|
|
518
531
|
#### `createQueryResource(config)`
|
|
519
532
|
|
|
520
533
|
Describe one API resource once and get its reads and writes on the shared cache.
|
|
521
534
|
|
|
522
535
|
A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
|
|
523
|
-
re-solve the same
|
|
524
|
-
over the current one, a list still shows what it showed before a comment was added
|
|
525
|
-
|
|
536
|
+
re-solve the same problems on every screen: a late answer for the previous page lands
|
|
537
|
+
over the current one, and a list still shows what it showed before a comment was added.
|
|
538
|
+
Here the reads are `useQuery` options (one key per
|
|
526
539
|
viewer, page and filter; the previous rows stay until the next answer) and every write puts
|
|
527
540
|
the server's own record into the cache and fetches the lists on screen again.
|
|
528
541
|
|
|
542
|
+
The factory supplies data operations. Mount a keyed
|
|
543
|
+
control inside `QueryContent` (your framework's query package: `@molecule/app-query-react`,
|
|
544
|
+
`-vue`, …) so it receives a loaded record and stays mounted during refresh.
|
|
545
|
+
For a server-backed toggle, use `useOptimisticValue` from your framework binding
|
|
546
|
+
(`@molecule/app-react`, `@molecule/app-vue`, …), or `OptimisticToggleButton` from its UI
|
|
547
|
+
package (`@molecule/app-ui-react`, …) for a boolean. Pass `toggle` as its
|
|
548
|
+
commit adapter, return the saved flag/count, and render the controller's value for the action
|
|
549
|
+
label too. Do not block clicks while that commit is pending. The resource example in
|
|
550
|
+
`@molecule/app-query-react` composes these APIs; a custom handler must provide the same
|
|
551
|
+
readiness and ordering itself.
|
|
552
|
+
|
|
529
553
|
Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
|
|
530
554
|
and the query provider are whatever the app bonded.
|
|
531
555
|
|
|
@@ -539,17 +563,27 @@ function createQueryResource<T, Create = Partial<T>, Update = Partial<T>>(
|
|
|
539
563
|
|
|
540
564
|
**Returns:** List and detail query options, and create, update, remove, toggle and refresh.
|
|
541
565
|
|
|
542
|
-
#### `
|
|
566
|
+
#### `QueryContent(props)`
|
|
543
567
|
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
568
|
+
The loaded-data branch receives a non-null document. Pending, failed initial reads and
|
|
569
|
+
missing records never mount that branch, so its actions cannot swallow an early click.
|
|
570
|
+
Cached data remains mounted during refresh, including a failed refresh. Status fallbacks
|
|
571
|
+
belong outside the list or record container rendered by `children`, and so does a refresh
|
|
572
|
+
line; the default fallbacks render nothing.
|
|
547
573
|
|
|
548
574
|
```typescript
|
|
549
|
-
function
|
|
575
|
+
function QueryContent<T>({
|
|
576
|
+
query,
|
|
577
|
+
children,
|
|
578
|
+
pending = null,
|
|
579
|
+
missing = null,
|
|
580
|
+
error,
|
|
581
|
+
}: QueryContentProps<T>): ReactNode
|
|
550
582
|
```
|
|
551
583
|
|
|
552
|
-
- `
|
|
584
|
+
- `props` — Query state, loaded content and optional status fallbacks.
|
|
585
|
+
|
|
586
|
+
**Returns:** Loaded content or the appropriate fallback.
|
|
553
587
|
|
|
554
588
|
#### `usePrefetch()`
|
|
555
589
|
|
|
@@ -610,6 +644,11 @@ For custom mutation handlers, `setData(saved)` publishes the server's response t
|
|
|
610
644
|
key and every observer. Use `setData(current => next)` for a local cache update. Render
|
|
611
645
|
`data` directly; a component-local copy stops observing later server responses. Prefer
|
|
612
646
|
`createQueryResource` when the API's reads and writes can share one resource definition.
|
|
647
|
+
Mount record-dependent actions inside `QueryContent` (or an explicit non-null data branch),
|
|
648
|
+
so a visible action cannot return early because its initial record is still missing.
|
|
649
|
+
Keep loaded actions mounted during refreshes. Server-backed toggles use `useOptimisticValue`
|
|
650
|
+
from `@molecule/app-react` or `OptimisticToggleButton` from `@molecule/app-ui-react` to keep
|
|
651
|
+
their displayed label and queued clicks on the same state while a save finishes.
|
|
613
652
|
|
|
614
653
|
```typescript
|
|
615
654
|
function useQuery<T>(options: QueryOptions<T> | null): UseQueryResult<T>
|
|
@@ -625,7 +664,7 @@ function useQuery<T>(options: QueryOptions<T> | null): UseQueryResult<T>
|
|
|
625
664
|
|
|
626
665
|
Peer dependencies:
|
|
627
666
|
|
|
628
|
-
- `@molecule/app-query` ^1.
|
|
667
|
+
- `@molecule/app-query` ^1.2.0
|
|
629
668
|
- `react` ^18.0.0 || ^19.0.0
|
|
630
669
|
|
|
631
670
|
### Runtime Dependencies
|
package/dist/index.d.ts
CHANGED
|
@@ -212,8 +212,8 @@
|
|
|
212
212
|
*
|
|
213
213
|
* ```tsx
|
|
214
214
|
* import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
|
|
215
|
-
* import { createQueryResource, useQuery } from '@molecule/app-query-react'
|
|
216
|
-
* import { useAuth, useOptimisticValue } from '@molecule/app-react'
|
|
215
|
+
* import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-react'
|
|
216
|
+
* import { useAuth, useOptimisticValue, useTranslation } from '@molecule/app-react'
|
|
217
217
|
*
|
|
218
218
|
* interface Invoice {
|
|
219
219
|
* id: string
|
|
@@ -231,21 +231,32 @@
|
|
|
231
231
|
*
|
|
232
232
|
* function InvoicePage({ id }: { id: string }) {
|
|
233
233
|
* const { user } = useAuth<{ id: string }>()
|
|
234
|
+
* const { t } = useTranslation()
|
|
234
235
|
* const viewer = user ? String(user.id) : 'anonymous'
|
|
235
|
-
* const
|
|
236
|
-
*
|
|
237
|
-
*
|
|
238
|
-
*
|
|
236
|
+
* const query = useQuery(invoices.detail(viewer, id))
|
|
237
|
+
* return (
|
|
238
|
+
* <QueryContent
|
|
239
|
+
* query={query}
|
|
240
|
+
* pending={<p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>}
|
|
241
|
+
* missing={<p role="alert">{t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' })}</p>}
|
|
242
|
+
* error={() => <p role="alert">{t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' })}</p>}
|
|
243
|
+
* >
|
|
244
|
+
* {(invoice) => <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />}
|
|
245
|
+
* </QueryContent>
|
|
246
|
+
* )
|
|
239
247
|
* }
|
|
240
248
|
*
|
|
241
249
|
* function FlagButton({ invoice, viewer }: { invoice: Invoice; viewer: string }) {
|
|
250
|
+
* const { t } = useTranslation()
|
|
242
251
|
* const flag = useOptimisticValue({
|
|
243
252
|
* value: invoice.flagged,
|
|
244
253
|
* commit: async (on) => (await invoices.toggle(viewer, invoice.id, 'flag', on)).flagged,
|
|
245
254
|
* })
|
|
246
255
|
* return (
|
|
247
|
-
* <button type=button aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
|
|
248
|
-
* {
|
|
256
|
+
* <button type="button" aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
|
|
257
|
+
* {flag.value
|
|
258
|
+
* ? t('invoice.unflag', undefined, { defaultValue: 'Unflag' })
|
|
259
|
+
* : t('invoice.flag', undefined, { defaultValue: 'Flag' })} {invoice.number}
|
|
249
260
|
* </button>
|
|
250
261
|
* )
|
|
251
262
|
* }
|
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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiYG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA;AAC1B,cAAc,kBAAkB,CAAA;AAChC,cAAc,eAAe,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -212,8 +212,8 @@
|
|
|
212
212
|
*
|
|
213
213
|
* ```tsx
|
|
214
214
|
* import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
|
|
215
|
-
* import { createQueryResource, useQuery } from '@molecule/app-query-react'
|
|
216
|
-
* import { useAuth, useOptimisticValue } from '@molecule/app-react'
|
|
215
|
+
* import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-react'
|
|
216
|
+
* import { useAuth, useOptimisticValue, useTranslation } from '@molecule/app-react'
|
|
217
217
|
*
|
|
218
218
|
* interface Invoice {
|
|
219
219
|
* id: string
|
|
@@ -231,21 +231,32 @@
|
|
|
231
231
|
*
|
|
232
232
|
* function InvoicePage({ id }: { id: string }) {
|
|
233
233
|
* const { user } = useAuth<{ id: string }>()
|
|
234
|
+
* const { t } = useTranslation()
|
|
234
235
|
* const viewer = user ? String(user.id) : 'anonymous'
|
|
235
|
-
* const
|
|
236
|
-
*
|
|
237
|
-
*
|
|
238
|
-
*
|
|
236
|
+
* const query = useQuery(invoices.detail(viewer, id))
|
|
237
|
+
* return (
|
|
238
|
+
* <QueryContent
|
|
239
|
+
* query={query}
|
|
240
|
+
* pending={<p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>}
|
|
241
|
+
* missing={<p role="alert">{t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' })}</p>}
|
|
242
|
+
* error={() => <p role="alert">{t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' })}</p>}
|
|
243
|
+
* >
|
|
244
|
+
* {(invoice) => <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />}
|
|
245
|
+
* </QueryContent>
|
|
246
|
+
* )
|
|
239
247
|
* }
|
|
240
248
|
*
|
|
241
249
|
* function FlagButton({ invoice, viewer }: { invoice: Invoice; viewer: string }) {
|
|
250
|
+
* const { t } = useTranslation()
|
|
242
251
|
* const flag = useOptimisticValue({
|
|
243
252
|
* value: invoice.flagged,
|
|
244
253
|
* commit: async (on) => (await invoices.toggle(viewer, invoice.id, 'flag', on)).flagged,
|
|
245
254
|
* })
|
|
246
255
|
* return (
|
|
247
|
-
* <button type=button aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
|
|
248
|
-
* {
|
|
256
|
+
* <button type="button" aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
|
|
257
|
+
* {flag.value
|
|
258
|
+
* ? t('invoice.unflag', undefined, { defaultValue: 'Unflag' })
|
|
259
|
+
* : t('invoice.flag', undefined, { defaultValue: 'Flag' })} {invoice.number}
|
|
249
260
|
* </button>
|
|
250
261
|
* )
|
|
251
262
|
* }
|
package/dist/resource.d.ts
CHANGED
|
@@ -1,102 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* One API resource on the shared query cache
|
|
3
|
-
*
|
|
2
|
+
* One API resource on the shared query cache. `createQueryResource` is framework-neutral, so it
|
|
3
|
+
* lives in `@molecule/app-query` (with its full documentation); this package re-exports it so
|
|
4
|
+
* React pages import it next to `useQuery` and `QueryContent`.
|
|
4
5
|
*
|
|
5
6
|
* @module
|
|
6
7
|
*/
|
|
7
|
-
|
|
8
|
-
|
|
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
|
-
* Options for a collection's whole page (rows plus totals), or a filtered collection path.
|
|
58
|
-
* Reads share this resource's mutation refresh and viewer isolation. `readPage` reads the
|
|
59
|
-
* canonical page response for `path`; row-only `list` reads keep a separate cache entry.
|
|
60
|
-
* Supply `removeFromPage` for opaque page envelopes to remove acknowledged deletions
|
|
61
|
-
* immediately and keep stale list responses from restoring them.
|
|
62
|
-
*/
|
|
63
|
-
listPage<Page>(viewer: string, params: Record<string, unknown>, readPage: (response: ResourceResponse) => Page, path?: string, removeFromPage?: (page: Page, id: string) => Page): QueryOptions<Page>;
|
|
64
|
-
/**
|
|
65
|
-
* `useQuery` options for one record, or null while `id` is not known yet (`useQuery(null)`
|
|
66
|
-
* observes nothing). A missing record resolves to null, not to an error.
|
|
67
|
-
*/
|
|
68
|
-
detail(viewer: string, id: string | null | undefined): QueryOptions<T | null> | null;
|
|
69
|
-
/** Creates a record, shows it in the cache and refreshes the lists on screen. */
|
|
70
|
-
create(viewer: string, input: Create): Promise<T>;
|
|
71
|
-
/** Updates a record, shows the saved record in the cache and refreshes the lists on screen. */
|
|
72
|
-
update(viewer: string, id: string, input: Update): Promise<T>;
|
|
73
|
-
/** Removes a record from detail and tracked row lists, then refreshes those lists. */
|
|
74
|
-
remove(viewer: string, id: string): Promise<void>;
|
|
75
|
-
/**
|
|
76
|
-
* Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
|
|
77
|
-
* `DELETE path/id/action` turns it off. Resolves with the saved record, so it is the `commit`
|
|
78
|
-
* of `useOptimisticValue`.
|
|
79
|
-
*/
|
|
80
|
-
toggle(viewer: string, id: string, action: string, on: boolean): Promise<T>;
|
|
81
|
-
/** Fetches the lists on screen again, after a change this resource did not make itself. */
|
|
82
|
-
refresh(viewer: string): Promise<void>;
|
|
83
|
-
}
|
|
84
|
-
/**
|
|
85
|
-
* Describe one API resource once and get its reads and writes on the shared cache.
|
|
86
|
-
*
|
|
87
|
-
* A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
|
|
88
|
-
* re-solve the same three problems on every screen: a late answer for the previous page lands
|
|
89
|
-
* over the current one, a list still shows what it showed before a comment was added, and a
|
|
90
|
-
* button is live before its record exists. Here the reads are `useQuery` options (one key per
|
|
91
|
-
* viewer, page and filter; the previous rows stay until the next answer) and every write puts
|
|
92
|
-
* the server's own record into the cache and fetches the lists on screen again.
|
|
93
|
-
*
|
|
94
|
-
* Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
|
|
95
|
-
* and the query provider are whatever the app bonded.
|
|
96
|
-
*
|
|
97
|
-
* @param config - The resource's name, path, HTTP client and response readers.
|
|
98
|
-
* @returns List and detail query options, and create, update, remove, toggle and refresh.
|
|
99
|
-
* @throws {Error} When a write's response holds no record.
|
|
100
|
-
*/
|
|
101
|
-
export declare function createQueryResource<T, Create = Partial<T>, Update = Partial<T>>(config: QueryResourceConfig<T>): QueryResource<T, Create, Update>;
|
|
8
|
+
export type { QueryResource, QueryResourceConfig, ResourceHttp, ResourceResponse, } from '@molecule/app-query';
|
|
9
|
+
export { createQueryResource } from '@molecule/app-query';
|
|
102
10
|
//# sourceMappingURL=resource.d.ts.map
|
package/dist/resource.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../src/resource.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../src/resource.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,YAAY,EACV,aAAa,EACb,mBAAmB,EACnB,YAAY,EACZ,gBAAgB,GACjB,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAA"}
|
package/dist/resource.js
CHANGED
|
@@ -1,160 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* One API resource on the shared query cache
|
|
3
|
-
*
|
|
2
|
+
* One API resource on the shared query cache. `createQueryResource` is framework-neutral, so it
|
|
3
|
+
* lives in `@molecule/app-query` (with its full documentation); this package re-exports it so
|
|
4
|
+
* React pages import it next to `useQuery` and `QueryContent`.
|
|
4
5
|
*
|
|
5
6
|
* @module
|
|
6
7
|
*/
|
|
7
|
-
|
|
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 removed = new Map();
|
|
38
|
-
const removals = (viewer) => removed.get(viewer) ?? new Set();
|
|
39
|
-
const recordId = (record) => {
|
|
40
|
-
const id = record != null ? record[idField] : undefined;
|
|
41
|
-
return typeof id === 'string' || typeof id === 'number' ? String(id) : undefined;
|
|
42
|
-
};
|
|
43
|
-
const withoutRemoved = (viewer, rows) => {
|
|
44
|
-
const ids = removed.get(viewer);
|
|
45
|
-
return ids?.size ? rows.filter((record) => !ids.has(recordId(record) ?? '')) : rows;
|
|
46
|
-
};
|
|
47
|
-
const projectPage = (viewer, page, remove) => {
|
|
48
|
-
if (!remove)
|
|
49
|
-
return page;
|
|
50
|
-
for (const id of removals(viewer))
|
|
51
|
-
page = remove(page, id);
|
|
52
|
-
return page;
|
|
53
|
-
};
|
|
54
|
-
const track = (viewer, options, remove) => {
|
|
55
|
-
const hash = hashQueryKey(options.key);
|
|
56
|
-
recent.delete(hash);
|
|
57
|
-
recent.set(hash, {
|
|
58
|
-
viewer,
|
|
59
|
-
options,
|
|
60
|
-
...(remove ? { remove: (page, id) => remove(page, id) } : {}),
|
|
61
|
-
});
|
|
62
|
-
for (const stale of [...recent.keys()].slice(0, -REFRESHED_LISTS))
|
|
63
|
-
recent.delete(stale);
|
|
64
|
-
return options;
|
|
65
|
-
};
|
|
66
|
-
const list = (viewer, params = {}) => {
|
|
67
|
-
const options = {
|
|
68
|
-
key: [config.name, viewer, 'list', params],
|
|
69
|
-
principal: viewer,
|
|
70
|
-
keepPreviousData: true,
|
|
71
|
-
fetch: async (signal) => withoutRemoved(viewer, readList(await config.http().get(base, { signal, params }))),
|
|
72
|
-
};
|
|
73
|
-
return track(viewer, options, (rows) => withoutRemoved(viewer, rows));
|
|
74
|
-
};
|
|
75
|
-
const refresh = async (viewer) => {
|
|
76
|
-
const client = getQueryClient();
|
|
77
|
-
client.invalidate([config.name, viewer, 'list']);
|
|
78
|
-
await Promise.all([...recent.values()]
|
|
79
|
-
.filter((entry) => entry.viewer === viewer)
|
|
80
|
-
.map(async (entry) => {
|
|
81
|
-
// fetch() deduplicates an existing request. It may have read before this write,
|
|
82
|
-
// so joining it alone cannot refresh the list after the mutation.
|
|
83
|
-
const pending = client.getState(entry.options.key).isFetching;
|
|
84
|
-
const fetch = () => client.fetch(entry.options).catch((_error) => {
|
|
85
|
-
// The mounted query presents its own failure; the mutation already succeeded.
|
|
86
|
-
});
|
|
87
|
-
await fetch();
|
|
88
|
-
if (pending) {
|
|
89
|
-
client.invalidate(entry.options.key);
|
|
90
|
-
await fetch();
|
|
91
|
-
}
|
|
92
|
-
}));
|
|
93
|
-
};
|
|
94
|
-
const saved = async (viewer, response, created = false) => {
|
|
95
|
-
const record = readOne(response);
|
|
96
|
-
if (record == null)
|
|
97
|
-
throw new Error(`${config.name}: the response held no record`);
|
|
98
|
-
const id = recordId(record);
|
|
99
|
-
if (id !== undefined) {
|
|
100
|
-
if (created)
|
|
101
|
-
removed.get(viewer)?.delete(id);
|
|
102
|
-
if (!removals(viewer).has(id))
|
|
103
|
-
getQueryClient().set(detailKey(viewer, id), record);
|
|
104
|
-
}
|
|
105
|
-
await refresh(viewer);
|
|
106
|
-
return record;
|
|
107
|
-
};
|
|
108
|
-
return {
|
|
109
|
-
list,
|
|
110
|
-
listPage: (viewer, params, readPage, path = base, removeFromPage) => track(viewer, {
|
|
111
|
-
key: [config.name, viewer, 'list', 'page', path, params],
|
|
112
|
-
principal: viewer,
|
|
113
|
-
keepPreviousData: true,
|
|
114
|
-
fetch: async (signal) => projectPage(viewer, readPage(await config.http().get(path, { signal, params })), removeFromPage),
|
|
115
|
-
}, removeFromPage),
|
|
116
|
-
detail: (viewer, id) => id == null || id === ''
|
|
117
|
-
? null
|
|
118
|
-
: {
|
|
119
|
-
key: detailKey(viewer, id),
|
|
120
|
-
principal: viewer,
|
|
121
|
-
fetch: async (signal) => {
|
|
122
|
-
if (removals(viewer).has(id))
|
|
123
|
-
return null;
|
|
124
|
-
try {
|
|
125
|
-
const record = readOne(await config.http().get(one(id), { signal }));
|
|
126
|
-
return removals(viewer).has(id) ? null : record;
|
|
127
|
-
}
|
|
128
|
-
catch (error) {
|
|
129
|
-
// A record that does not exist is an answer, not a failed load.
|
|
130
|
-
if (error?.status === 404)
|
|
131
|
-
return null;
|
|
132
|
-
throw error;
|
|
133
|
-
}
|
|
134
|
-
},
|
|
135
|
-
},
|
|
136
|
-
create: async (viewer, input) => saved(viewer, await config.http().post(base, input), true),
|
|
137
|
-
update: async (viewer, id, input) => saved(viewer, await config.http()[config.updateMethod ?? 'put'](one(id), input)),
|
|
138
|
-
remove: async (viewer, id) => {
|
|
139
|
-
await config.http().delete(one(id));
|
|
140
|
-
const ids = removed.get(viewer) ?? new Set();
|
|
141
|
-
ids.add(id);
|
|
142
|
-
removed.set(viewer, ids);
|
|
143
|
-
const client = getQueryClient();
|
|
144
|
-
client.set(detailKey(viewer, id), null);
|
|
145
|
-
for (const entry of recent.values()) {
|
|
146
|
-
if (entry.viewer !== viewer || !entry.remove)
|
|
147
|
-
continue;
|
|
148
|
-
const page = client.getState(entry.options.key).data;
|
|
149
|
-
if (page !== undefined)
|
|
150
|
-
client.set(entry.options.key, entry.remove(page, id));
|
|
151
|
-
}
|
|
152
|
-
await refresh(viewer);
|
|
153
|
-
},
|
|
154
|
-
toggle: async (viewer, id, action, on) => {
|
|
155
|
-
const path = `${one(id)}/${action.replace(/^\/+/, '')}`;
|
|
156
|
-
return saved(viewer, on ? await config.http().post(path) : await config.http().delete(path));
|
|
157
|
-
},
|
|
158
|
-
refresh,
|
|
159
|
-
};
|
|
160
|
-
}
|
|
8
|
+
export { createQueryResource } from '@molecule/app-query';
|
package/dist/usePrefetch.d.ts
CHANGED
|
@@ -1,17 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Warm the cache ahead of a navigation.
|
|
2
|
+
* Warm the cache ahead of a navigation. `prefetchQuery` itself is framework-neutral and lives in
|
|
3
|
+
* `@molecule/app-query`; this module re-exports it and adds the React hook and link handlers.
|
|
3
4
|
*
|
|
4
5
|
* @module
|
|
5
6
|
*/
|
|
6
7
|
import type { QueryOptions } from '@molecule/app-query';
|
|
7
|
-
|
|
8
|
-
* Warms the cache for a document, when the connection can afford it (see
|
|
9
|
-
* `shouldPrefetch()` in the core). Safe to call repeatedly: a fresh or
|
|
10
|
-
* in-flight document is skipped, and failures are swallowed.
|
|
11
|
-
*
|
|
12
|
-
* @param options - Key, fetch, freshness.
|
|
13
|
-
*/
|
|
14
|
-
export declare function prefetchQuery<T>(options: QueryOptions<T>): void;
|
|
8
|
+
export { prefetchQuery } from '@molecule/app-query';
|
|
15
9
|
/**
|
|
16
10
|
* A stable `prefetch(options)` function for event handlers.
|
|
17
11
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usePrefetch.d.ts","sourceRoot":"","sources":["../src/usePrefetch.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"usePrefetch.d.ts","sourceRoot":"","sources":["../src/usePrefetch.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAGvD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAEnD;;;;GAIG;AACH,wBAAgB,WAAW,IAAI,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,KAAK,IAAI,CAEnE;AAED,wDAAwD;AACxD,MAAM,WAAW,mBAAmB;IAClC,cAAc,EAAE,MAAM,IAAI,CAAA;IAC1B,OAAO,EAAE,MAAM,IAAI,CAAA;IACnB,YAAY,EAAE,MAAM,IAAI,CAAA;CACzB;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,mBAAmB,CAGpF"}
|
package/dist/usePrefetch.js
CHANGED
|
@@ -1,22 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Warm the cache ahead of a navigation.
|
|
2
|
+
* Warm the cache ahead of a navigation. `prefetchQuery` itself is framework-neutral and lives in
|
|
3
|
+
* `@molecule/app-query`; this module re-exports it and adds the React hook and link handlers.
|
|
3
4
|
*
|
|
4
5
|
* @module
|
|
5
6
|
*/
|
|
6
7
|
import { useCallback } from 'react';
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
* Warms the cache for a document, when the connection can afford it (see
|
|
10
|
-
* `shouldPrefetch()` in the core). Safe to call repeatedly: a fresh or
|
|
11
|
-
* in-flight document is skipped, and failures are swallowed.
|
|
12
|
-
*
|
|
13
|
-
* @param options - Key, fetch, freshness.
|
|
14
|
-
*/
|
|
15
|
-
export function prefetchQuery(options) {
|
|
16
|
-
if (!shouldPrefetch())
|
|
17
|
-
return;
|
|
18
|
-
getQueryClient().prefetch(options);
|
|
19
|
-
}
|
|
8
|
+
import { prefetchQuery } from '@molecule/app-query';
|
|
9
|
+
export { prefetchQuery } from '@molecule/app-query';
|
|
20
10
|
/**
|
|
21
11
|
* A stable `prefetch(options)` function for event handlers.
|
|
22
12
|
*
|
package/dist/useQuery.d.ts
CHANGED
|
@@ -39,6 +39,11 @@ import type { UseQueryResult } from './types.js';
|
|
|
39
39
|
* key and every observer. Use `setData(current => next)` for a local cache update. Render
|
|
40
40
|
* `data` directly; a component-local copy stops observing later server responses. Prefer
|
|
41
41
|
* `createQueryResource` when the API's reads and writes can share one resource definition.
|
|
42
|
+
* Mount record-dependent actions inside `QueryContent` (or an explicit non-null data branch),
|
|
43
|
+
* so a visible action cannot return early because its initial record is still missing.
|
|
44
|
+
* Keep loaded actions mounted during refreshes. Server-backed toggles use `useOptimisticValue`
|
|
45
|
+
* from `@molecule/app-react` or `OptimisticToggleButton` from `@molecule/app-ui-react` to keep
|
|
46
|
+
* their displayed label and queued clicks on the same state while a save finishes.
|
|
42
47
|
*
|
|
43
48
|
* @param options - Key, fetch, freshness, and optionally `principal` with
|
|
44
49
|
* `keepPreviousData`; or `null`.
|
package/dist/useQuery.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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
|
|
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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,cAAc,CAAC,CAAC,CAAC,CAkG9E"}
|
package/dist/useQuery.js
CHANGED
|
@@ -46,6 +46,11 @@ const IDLE = {
|
|
|
46
46
|
* key and every observer. Use `setData(current => next)` for a local cache update. Render
|
|
47
47
|
* `data` directly; a component-local copy stops observing later server responses. Prefer
|
|
48
48
|
* `createQueryResource` when the API's reads and writes can share one resource definition.
|
|
49
|
+
* Mount record-dependent actions inside `QueryContent` (or an explicit non-null data branch),
|
|
50
|
+
* so a visible action cannot return early because its initial record is still missing.
|
|
51
|
+
* Keep loaded actions mounted during refreshes. Server-backed toggles use `useOptimisticValue`
|
|
52
|
+
* from `@molecule/app-react` or `OptimisticToggleButton` from `@molecule/app-ui-react` to keep
|
|
53
|
+
* their displayed label and queued clicks on the same state while a save finishes.
|
|
49
54
|
*
|
|
50
55
|
* @param options - Key, fetch, freshness, and optionally `principal` with
|
|
51
56
|
* `keepPreviousData`; or `null`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@molecule/app-query-react",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.1",
|
|
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",
|
|
@@ -36,11 +36,11 @@
|
|
|
36
36
|
"directory": "packages/app/features/query-react"
|
|
37
37
|
},
|
|
38
38
|
"peerDependencies": {
|
|
39
|
-
"@molecule/app-query": "^1.
|
|
39
|
+
"@molecule/app-query": "^1.2.0",
|
|
40
40
|
"react": "^18.0.0 || ^19.0.0"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
|
-
"@molecule/app-query": "1.
|
|
43
|
+
"@molecule/app-query": "1.2.0",
|
|
44
44
|
"@molecule/app-query-memory": "1.0.5",
|
|
45
45
|
"@molecule/app-query-tanstack": "1.0.5",
|
|
46
46
|
"@types/node": "26.6.5",
|