@molecule/app-query-angular 0.0.0-stage → 0.0.1-stage
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/LICENSE +202 -0
- package/README.md +979 -2
- package/dist/index.d.ts +464 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +464 -0
- package/dist/index.js.map +1 -0
- package/dist/query-content.component.d.ts +73 -0
- package/dist/query-content.component.d.ts.map +1 -0
- package/dist/query-content.component.js +148 -0
- package/dist/query-content.component.js.map +1 -0
- package/dist/resource.d.ts +11 -0
- package/dist/resource.d.ts.map +1 -0
- package/dist/resource.js +10 -0
- package/dist/resource.js.map +1 -0
- package/dist/types.d.ts +70 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/use-prefetch.d.ts +46 -0
- package/dist/use-prefetch.d.ts.map +1 -0
- package/dist/use-prefetch.js +31 -0
- package/dist/use-prefetch.js.map +1 -0
- package/dist/use-query.d.ts +72 -0
- package/dist/use-query.d.ts.map +1 -0
- package/dist/use-query.js +265 -0
- package/dist/use-query.js.map +1 -0
- package/package.json +73 -4
package/README.md
CHANGED
|
@@ -1,3 +1,980 @@
|
|
|
1
|
-
|
|
1
|
+
<!--
|
|
2
|
+
AUTO-GENERATED — DO NOT EDIT THIS FILE.
|
|
3
|
+
Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
|
|
4
|
+
Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
|
|
5
|
+
To change this document, edit the module-level JSDoc in src/index.ts.
|
|
6
|
+
Generated: 2026-11-14T15:07:28.989Z
|
|
7
|
+
-->
|
|
2
8
|
|
|
3
|
-
|
|
9
|
+
# @molecule/app-query-angular
|
|
10
|
+
|
|
11
|
+
Angular hooks for `@molecule/app-query` — the Angular counterpart of
|
|
12
|
+
`@molecule/app-query-react`, with the same exports, the same contracts and
|
|
13
|
+
the same rendered result for the same input.
|
|
14
|
+
|
|
15
|
+
**Load page data with {@link useQuery}, not a hand-written load effect.** An
|
|
16
|
+
effect that cancels its own request on cleanup (a `cancelled` flag, or an
|
|
17
|
+
`AbortController`) re-runs its cleanup whenever one of its tracked
|
|
18
|
+
dependencies is a function created inline each run — and its own guard then
|
|
19
|
+
returns without refetching, so the response is discarded whenever it arrives
|
|
20
|
+
after a re-render: always on a remote server, never on localhost, which is
|
|
21
|
+
why the page passes locally and fails on the live URL. `useQuery`
|
|
22
|
+
subscribes once per key, keeps its request stable across template refreshes,
|
|
23
|
+
and aborts it only when the key changes or the component is destroyed.
|
|
24
|
+
|
|
25
|
+
{@link useQuery} observes one document from the app's shared cache and
|
|
26
|
+
returns cached data on the first read; {@link usePrefetch} and
|
|
27
|
+
{@link intentPrefetchProps} warm a document when a person is about to open
|
|
28
|
+
it. Together they make a detail page open with no loading state.
|
|
29
|
+
|
|
30
|
+
This package needs a bonded client: install `@molecule/app-query` with a bond
|
|
31
|
+
(`@molecule/app-query-memory`, or `@molecule/app-query-tanstack`) and call the
|
|
32
|
+
bond's `setProvider(provider)` once at startup (the scaffold's `app/src/bonds/`
|
|
33
|
+
does this). Call the hooks in an injection context — a component field
|
|
34
|
+
initializer or constructor. A component whose options change with its own
|
|
35
|
+
state passes a `Signal` of options (an `input()`/`computed()`), and every
|
|
36
|
+
change is followed on the same instance, the way React re-renders `useQuery`
|
|
37
|
+
with a new options object.
|
|
38
|
+
|
|
39
|
+
> **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
|
|
40
|
+
> It is written to be read by coding agents as much as by people, and is generated from this
|
|
41
|
+
> package's source — edit `src/index.ts` JSDoc, not this file.
|
|
42
|
+
|
|
43
|
+
## Quick Start
|
|
44
|
+
|
|
45
|
+
```typescript
|
|
46
|
+
import { Component, OnChanges, computed, input } from '@angular/core'
|
|
47
|
+
import { getClient, isHttpError } from '@molecule/app-http'
|
|
48
|
+
import { t } from '@molecule/app-i18n'
|
|
49
|
+
import { intentPrefetchProps, useQuery } from '@molecule/app-query-angular'
|
|
50
|
+
|
|
51
|
+
interface PackageDocument {
|
|
52
|
+
name: string
|
|
53
|
+
description: string
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const packageQuery = (name: string) => ({
|
|
57
|
+
key: ['package', name],
|
|
58
|
+
fetch: async (signal: AbortSignal): Promise<PackageDocument | null> => {
|
|
59
|
+
try {
|
|
60
|
+
const response = await getClient().get<PackageDocument | null>(
|
|
61
|
+
`/data/packages/${encodeURIComponent(name)}.json`,
|
|
62
|
+
{ signal },
|
|
63
|
+
)
|
|
64
|
+
return response.data
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (isHttpError(error) && error.status === 404) return null
|
|
67
|
+
throw error
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
// A link warms its document at the first sign of intent: the handlers
|
|
73
|
+
// `intentPrefetchProps` returns are named after the DOM events an Angular
|
|
74
|
+
// template binds, so a component puts them on its host listeners.
|
|
75
|
+
@Component({
|
|
76
|
+
selector: 'a[mol-package-link]',
|
|
77
|
+
template: '<ng-content></ng-content>',
|
|
78
|
+
inputs: ['name'],
|
|
79
|
+
host: {
|
|
80
|
+
'(pointerenter)': 'warm.pointerenter()',
|
|
81
|
+
'(focus)': 'warm.focus()',
|
|
82
|
+
'(touchstart)': 'warm.touchstart()',
|
|
83
|
+
},
|
|
84
|
+
})
|
|
85
|
+
export class PackageLink implements OnChanges {
|
|
86
|
+
name = ''
|
|
87
|
+
|
|
88
|
+
warm = intentPrefetchProps(packageQuery(this.name))
|
|
89
|
+
|
|
90
|
+
ngOnChanges(): void {
|
|
91
|
+
this.warm = intentPrefetchProps(packageQuery(this.name))
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// The page reads the document synchronously when it is cached (a warmed page
|
|
96
|
+
// opens with no loading state) and follows a changed name on the same
|
|
97
|
+
// instance. Until a name arrives, `null` observes nothing.
|
|
98
|
+
@Component({
|
|
99
|
+
selector: 'mol-package-page',
|
|
100
|
+
template: `
|
|
101
|
+
@if (query.status === 'error') {
|
|
102
|
+
<p role="alert">
|
|
103
|
+
{{ t('packages.loadFailed', undefined, { defaultValue: 'Unable to load package.' }) }}
|
|
104
|
+
</p>
|
|
105
|
+
} @else if (query.status === 'idle' || query.status === 'loading') {
|
|
106
|
+
<p role="status">{{ t('common.loading', undefined, { defaultValue: 'Loading…' }) }}</p>
|
|
107
|
+
} @else if (query.data === null) {
|
|
108
|
+
<p>{{ t('packages.notFound', undefined, { defaultValue: 'Package not found.' }) }}</p>
|
|
109
|
+
} @else {
|
|
110
|
+
<article>
|
|
111
|
+
<h1>{{ query.data?.name }}</h1>
|
|
112
|
+
<p>{{ query.data?.description }}</p>
|
|
113
|
+
</article>
|
|
114
|
+
}
|
|
115
|
+
`,
|
|
116
|
+
})
|
|
117
|
+
export class PackagePage {
|
|
118
|
+
// Expose the i18n function so every template binding re-reads it.
|
|
119
|
+
protected readonly t = t
|
|
120
|
+
readonly name = input('')
|
|
121
|
+
|
|
122
|
+
readonly query = useQuery<PackageDocument | null>(
|
|
123
|
+
computed(() => (this.name() ? packageQuery(this.name()) : null)),
|
|
124
|
+
)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// `<a [mol-package-link][name]="next" [href]="href">{{ next }}</a>` warms the
|
|
128
|
+
// next package while the reader hovers, focuses or touches the link, so the
|
|
129
|
+
// page it opens renders from cache with no loading state.
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
A list whose page and filter live in the URL: derive the key from the route
|
|
133
|
+
(a `computed` over the route inputs) and pass `keepPreviousData` with a
|
|
134
|
+
`principal`, so a page/filter change keeps the rows already on screen until
|
|
135
|
+
the next page answers. The app's HTTP client sends the session, so the viewer
|
|
136
|
+
is part of what the answer depends on: key on it and pass the same value as
|
|
137
|
+
`principal` — an account switch then drops the previous account's rows at
|
|
138
|
+
once. Pass `null` while the session is still being restored (`status ===
|
|
139
|
+
'loading'`; the HTTP client holds the request until then anyway), so
|
|
140
|
+
restoring a session never swaps a key that already rendered rows.
|
|
141
|
+
|
|
142
|
+
```typescript
|
|
143
|
+
import { Component, computed, input } from '@angular/core'
|
|
144
|
+
import { getClient, unwrapList } from '@molecule/app-http'
|
|
145
|
+
import { t } from '@molecule/app-i18n'
|
|
146
|
+
import { useQuery } from '@molecule/app-query-angular'
|
|
147
|
+
|
|
148
|
+
interface Invoice {
|
|
149
|
+
id: string
|
|
150
|
+
number: string
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
@Component({
|
|
154
|
+
selector: 'mol-invoice-list',
|
|
155
|
+
template: `
|
|
156
|
+
@if (query.status === 'loading' || query.isFetching) {
|
|
157
|
+
<p role="status">{{ t('common.loading', undefined, { defaultValue: 'Loading…' }) }}</p>
|
|
158
|
+
}
|
|
159
|
+
@if (query.status === 'error') {
|
|
160
|
+
<p role="alert">
|
|
161
|
+
{{ t('invoices.loadFailed', undefined, { defaultValue: 'Unable to load invoices.' }) }}
|
|
162
|
+
</p>
|
|
163
|
+
}
|
|
164
|
+
<ul>
|
|
165
|
+
@for (invoice of query.data ?? []; track invoice.id) {
|
|
166
|
+
<li>
|
|
167
|
+
<a [href]="'/invoices/' + invoice.id">{{ invoice.number }}</a>
|
|
168
|
+
</li>
|
|
169
|
+
}
|
|
170
|
+
</ul>
|
|
171
|
+
@if (!query.isPreviousData && query.data?.length === 0) {
|
|
172
|
+
<p>{{ t('invoices.empty', undefined, { defaultValue: 'No invoices yet.' }) }}</p>
|
|
173
|
+
}
|
|
174
|
+
<a [href]="nextHref()">{{ t('common.next', undefined, { defaultValue: 'Next page' }) }}</a>
|
|
175
|
+
`,
|
|
176
|
+
})
|
|
177
|
+
export class InvoiceList {
|
|
178
|
+
// Expose the i18n function so every template binding re-reads it.
|
|
179
|
+
protected readonly t = t
|
|
180
|
+
// The viewer whose invoices these are (also in the key).
|
|
181
|
+
readonly viewer = input('anonymous')
|
|
182
|
+
// The page to show.
|
|
183
|
+
readonly page = input(1)
|
|
184
|
+
|
|
185
|
+
readonly query = useQuery<Invoice[]>(
|
|
186
|
+
computed(() => ({
|
|
187
|
+
key: ['invoices', this.viewer(), this.page()],
|
|
188
|
+
principal: this.viewer(),
|
|
189
|
+
keepPreviousData: true,
|
|
190
|
+
fetch: async (signal: AbortSignal) =>
|
|
191
|
+
unwrapList<Invoice>(
|
|
192
|
+
await getClient().get('/api/invoices', {
|
|
193
|
+
signal,
|
|
194
|
+
params: { limit: 20, offset: (this.page() - 1) * 20 },
|
|
195
|
+
}),
|
|
196
|
+
),
|
|
197
|
+
})),
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
readonly nextHref = computed(() => `/invoices?page=${this.page() + 1}`)
|
|
201
|
+
}
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
A mutation or a failed load has to change a page that is ALREADY mounted, and
|
|
205
|
+
the cache never starts that request by itself: `set()` paints a mutation's own
|
|
206
|
+
response, `invalidate()` marks what it affects for the next mount, and an
|
|
207
|
+
explicit `fetch()` retries into the mounted page.
|
|
208
|
+
|
|
209
|
+
```typescript
|
|
210
|
+
import { Component, input } from '@angular/core'
|
|
211
|
+
import { getClient } from '@molecule/app-http'
|
|
212
|
+
import { t } from '@molecule/app-i18n'
|
|
213
|
+
import { getQueryClient } from '@molecule/app-query'
|
|
214
|
+
|
|
215
|
+
// The key names what the document actually depends on — here the signed-in
|
|
216
|
+
// principal, the filter and the page. Another principal's feed is a
|
|
217
|
+
// different document, so an invalidation scoped to this one leaves it alone.
|
|
218
|
+
const feedKey = (principal: string, filter: string, page: number) =>
|
|
219
|
+
['feed', principal, filter, page] as const
|
|
220
|
+
|
|
221
|
+
const feedOptions = (principal: string, filter: string, page: number) => ({
|
|
222
|
+
key: feedKey(principal, filter, page),
|
|
223
|
+
fetch: async (signal: AbortSignal) =>
|
|
224
|
+
(await getClient().get(`/api/feeds/${filter}`, { signal, params: { page } })).data,
|
|
225
|
+
})
|
|
226
|
+
|
|
227
|
+
async function setFollowing(principal: string, authorId: string, follow: boolean): Promise<void> {
|
|
228
|
+
const client = getQueryClient()
|
|
229
|
+
const http = getClient()
|
|
230
|
+
const { data: body } = follow
|
|
231
|
+
? await http.post<{ feed: unknown }>(`/api/follows/${authorId}`)
|
|
232
|
+
: await http.delete<{ feed: unknown }>(`/api/follows/${authorId}`)
|
|
233
|
+
// The response IS the document: paint it now, with no second round trip.
|
|
234
|
+
// (If it were only a count or a flag, skip set() and invalidate() instead.)
|
|
235
|
+
client.set(feedKey(principal, 'following', 1), body.feed)
|
|
236
|
+
// Future reads of every feed this principal owns are stale.
|
|
237
|
+
client.invalidate(['feed', principal])
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
@Component({
|
|
241
|
+
selector: 'button[mol-feed-retry]',
|
|
242
|
+
template: `{{ t('common.retry', undefined, { defaultValue: 'Retry' }) }}`,
|
|
243
|
+
host: { type: 'button', '(click)': 'retry()' },
|
|
244
|
+
})
|
|
245
|
+
export class FeedRetry {
|
|
246
|
+
// Expose the i18n function so every template binding re-reads it.
|
|
247
|
+
protected readonly t = t
|
|
248
|
+
readonly principal = input.required<string>()
|
|
249
|
+
|
|
250
|
+
retry(): void {
|
|
251
|
+
// invalidate() alone would leave the mounted page on its error;
|
|
252
|
+
// an explicit fetch retries into it. useQuery shows the outcome.
|
|
253
|
+
void getQueryClient()
|
|
254
|
+
.fetch(feedOptions(this.principal(), 'following', 1))
|
|
255
|
+
.catch((_error) => {
|
|
256
|
+
// The mounted useQuery observer presents this failure via status/error.
|
|
257
|
+
})
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
One API resource described once, for every page that reads or changes it.
|
|
263
|
+
`createQueryResource` returns the list and detail reads as `useQuery` options
|
|
264
|
+
and the writes as functions that put the server's record into the cache and
|
|
265
|
+
fetch the lists on screen again, so a page never mirrors a response into
|
|
266
|
+
component state. A flag the API models as a sub-path (`POST
|
|
267
|
+
/invoices/:id/flag`, `DELETE` to clear it) is `toggle`, which resolves with
|
|
268
|
+
the saved record and is the `commit` of `OptimisticToggleButton` (from
|
|
269
|
+
`@molecule/app-ui-angular`).
|
|
270
|
+
|
|
271
|
+
```typescript
|
|
272
|
+
import { Component, computed, input } from '@angular/core'
|
|
273
|
+
import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
|
|
274
|
+
import { t } from '@molecule/app-i18n'
|
|
275
|
+
import { OptimisticToggleButton } from '@molecule/app-ui-angular'
|
|
276
|
+
import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-angular'
|
|
277
|
+
|
|
278
|
+
interface Invoice {
|
|
279
|
+
id: string
|
|
280
|
+
number: string
|
|
281
|
+
flagged: boolean
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export const invoices = createQueryResource<Invoice>({
|
|
285
|
+
name: 'invoices',
|
|
286
|
+
path: '/invoices',
|
|
287
|
+
http: getClient,
|
|
288
|
+
readList: (response) => unwrapList<Invoice>(response),
|
|
289
|
+
readOne: (response) => unwrapSingle<Invoice | null>(response),
|
|
290
|
+
})
|
|
291
|
+
|
|
292
|
+
// The record's own action: a flag control whose click shows at once, whose
|
|
293
|
+
// save follows, and whose label goes back to the server's value only when the
|
|
294
|
+
// save fails. OptimisticToggleButton takes the server value as an input, so a
|
|
295
|
+
// fresh query answer updates it after a completed save.
|
|
296
|
+
@Component({
|
|
297
|
+
selector: 'mol-flag-control',
|
|
298
|
+
template: `
|
|
299
|
+
<button type="button" mol-optimistic-toggle-button [value]="invoice().flagged" [commit]="save">
|
|
300
|
+
<span slot="activeLabel">{{
|
|
301
|
+
t('invoice.unflag', undefined, { defaultValue: 'Unflag' })
|
|
302
|
+
}}</span>
|
|
303
|
+
<span slot="inactiveLabel">{{ t('invoice.flag', undefined, { defaultValue: 'Flag' }) }}</span>
|
|
304
|
+
{{ invoice().number }}
|
|
305
|
+
</button>
|
|
306
|
+
`,
|
|
307
|
+
imports: [OptimisticToggleButton],
|
|
308
|
+
})
|
|
309
|
+
export class InvoiceFlagControl {
|
|
310
|
+
readonly invoice = input.required<Invoice>()
|
|
311
|
+
readonly viewer = input.required<string>()
|
|
312
|
+
protected readonly t = t
|
|
313
|
+
|
|
314
|
+
readonly save = async (flagged: boolean): Promise<boolean> =>
|
|
315
|
+
(await invoices.toggle(this.viewer(), this.invoice().id, 'flag', flagged)).flagged
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// Render the record's own container (here the flag control) through
|
|
319
|
+
// QueryContent: its children template runs only with a loaded, non-null
|
|
320
|
+
// document, so an action can never swallow an early click. Every status
|
|
321
|
+
// line stays beside it.
|
|
322
|
+
@Component({
|
|
323
|
+
selector: 'mol-invoice-page',
|
|
324
|
+
template: `
|
|
325
|
+
<mol-query-content
|
|
326
|
+
[query]="query"
|
|
327
|
+
[pending]="pending"
|
|
328
|
+
[missing]="missing"
|
|
329
|
+
[error]="failed"
|
|
330
|
+
[children]="content"
|
|
331
|
+
>
|
|
332
|
+
<ng-template #pending>
|
|
333
|
+
<p role="status">{{ t('common.loading', undefined, { defaultValue: 'Loading…' }) }}</p>
|
|
334
|
+
</ng-template>
|
|
335
|
+
<ng-template #missing>
|
|
336
|
+
<p role="alert">
|
|
337
|
+
{{ t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' }) }}
|
|
338
|
+
</p>
|
|
339
|
+
</ng-template>
|
|
340
|
+
<ng-template #failed let-_error>
|
|
341
|
+
<p role="alert">
|
|
342
|
+
{{ t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' }) }}
|
|
343
|
+
</p>
|
|
344
|
+
</ng-template>
|
|
345
|
+
<ng-template #content let-invoice>
|
|
346
|
+
<mol-flag-control [invoice]="invoice" [viewer]="viewer()"></mol-flag-control>
|
|
347
|
+
</ng-template>
|
|
348
|
+
</mol-query-content>
|
|
349
|
+
`,
|
|
350
|
+
imports: [QueryContent, InvoiceFlagControl],
|
|
351
|
+
})
|
|
352
|
+
export class InvoicePage {
|
|
353
|
+
// Expose the i18n function so every template binding re-reads it.
|
|
354
|
+
protected readonly t = t
|
|
355
|
+
readonly id = input('')
|
|
356
|
+
readonly viewer = input('')
|
|
357
|
+
|
|
358
|
+
readonly query = useQuery(
|
|
359
|
+
computed(() => (this.viewer() && this.id() ? invoices.detail(this.viewer(), this.id()) : null)),
|
|
360
|
+
)
|
|
361
|
+
}
|
|
362
|
+
```
|
|
363
|
+
|
|
364
|
+
A pager needs the whole response, including its total. Keep that read on the
|
|
365
|
+
same resource as its mutations, including alternate list paths; a separate
|
|
366
|
+
hand-written options object is outside the resource's refresh tracking.
|
|
367
|
+
|
|
368
|
+
```typescript
|
|
369
|
+
import { getClient } from '@molecule/app-http'
|
|
370
|
+
import { createQueryResource } from '@molecule/app-query-angular'
|
|
371
|
+
|
|
372
|
+
interface TicketPage {
|
|
373
|
+
tickets: { id: string; subject: string }[]
|
|
374
|
+
total: number
|
|
375
|
+
}
|
|
376
|
+
const tickets = createQueryResource<TicketPage['tickets'][number]>({
|
|
377
|
+
name: 'tickets',
|
|
378
|
+
path: '/tickets',
|
|
379
|
+
http: getClient,
|
|
380
|
+
readOne: (response) => response.data as TicketPage['tickets'][number],
|
|
381
|
+
})
|
|
382
|
+
const page = tickets.listPage(
|
|
383
|
+
'agent-1',
|
|
384
|
+
{ limit: 10, offset: 20 },
|
|
385
|
+
(response) => response.data as TicketPage,
|
|
386
|
+
)
|
|
387
|
+
// useQuery(page) observes both rows and total. tickets.create/update/remove/toggle
|
|
388
|
+
// and tickets.refresh('agent-1') refresh this page too.
|
|
389
|
+
// A second list can use tickets.listPage(viewer, params, readPage, '/tickets/open').
|
|
390
|
+
// Use one canonical page reader per path; list() still returns only its own rows.
|
|
391
|
+
// For immediate deletion from an opaque page, add a fifth argument:
|
|
392
|
+
// (page, id) => {
|
|
393
|
+
// const rows = page.tickets.filter((row) => String(row.id) !== id)
|
|
394
|
+
// return { ...page, tickets: rows, total: page.total - (page.tickets.length - rows.length) }
|
|
395
|
+
// }
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
A resource mutation also waits out a pre-mutation list request before fetching again;
|
|
399
|
+
joining that older in-flight read alone would leave the new record absent.
|
|
400
|
+
Successful deletion removes a row immediately, including one just created through the
|
|
401
|
+
resource. Stale reads cannot restore acknowledged deletions for that viewer; an explicit
|
|
402
|
+
successful create can recreate the identity. Opaque listPage envelopes need their own
|
|
403
|
+
removeFromPage adapter; no row or total property is guessed.
|
|
404
|
+
|
|
405
|
+
## Type
|
|
406
|
+
|
|
407
|
+
`feature`
|
|
408
|
+
|
|
409
|
+
## Installation
|
|
410
|
+
|
|
411
|
+
```bash
|
|
412
|
+
npm install @molecule/app-query-angular @angular/common @angular/core @angular/platform-browser @molecule/app-query
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
## API
|
|
416
|
+
|
|
417
|
+
### Interfaces
|
|
418
|
+
|
|
419
|
+
#### `ResourceResponse`
|
|
420
|
+
|
|
421
|
+
The part of an HTTP response a resource reads.
|
|
422
|
+
|
|
423
|
+
```typescript
|
|
424
|
+
interface ResourceResponse {
|
|
425
|
+
/** The parsed response body. */
|
|
426
|
+
data: unknown
|
|
427
|
+
}
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
#### `ResourceHttp`
|
|
431
|
+
|
|
432
|
+
The HTTP client a resource calls: the app's own bonded client (`getClient()` from
|
|
433
|
+
`@molecule/app-http`) has this shape. Only what a resource uses is named here.
|
|
434
|
+
|
|
435
|
+
```typescript
|
|
436
|
+
interface ResourceHttp {
|
|
437
|
+
/** Reads `path`; `signal` cancels it and `params` become the query string. */
|
|
438
|
+
get(
|
|
439
|
+
path: string,
|
|
440
|
+
options?: { signal?: AbortSignal; params?: Record<string, unknown> },
|
|
441
|
+
): Promise<ResourceResponse>
|
|
442
|
+
/** Creates at `path`. */
|
|
443
|
+
post(path: string, body?: unknown): Promise<ResourceResponse>
|
|
444
|
+
/** Replaces at `path`. */
|
|
445
|
+
put(path: string, body?: unknown): Promise<ResourceResponse>
|
|
446
|
+
/** Changes part of the record at `path`. */
|
|
447
|
+
patch(path: string, body?: unknown): Promise<ResourceResponse>
|
|
448
|
+
/** Removes at `path`. */
|
|
449
|
+
delete(path: string): Promise<ResourceResponse>
|
|
450
|
+
}
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
#### `QueryResourceConfig`
|
|
454
|
+
|
|
455
|
+
What {@link createQueryResource} needs to know about one resource.
|
|
456
|
+
|
|
457
|
+
```typescript
|
|
458
|
+
interface QueryResourceConfig<T> {
|
|
459
|
+
/** The first element of every cache key of this resource, e.g. `'invoices'`. */
|
|
460
|
+
name: string
|
|
461
|
+
/** The collection's path under the API base, e.g. `'/invoices'`. */
|
|
462
|
+
path: string
|
|
463
|
+
/** The app's HTTP client, read on every call so a client bonded later is the one used. */
|
|
464
|
+
http: () => ResourceHttp
|
|
465
|
+
/** The field a record is addressed by in a URL. Defaults to `'id'`. */
|
|
466
|
+
id?: keyof T & string
|
|
467
|
+
/** The HTTP method the API updates a record with. Defaults to `'put'`. */
|
|
468
|
+
updateMethod?: 'put' | 'patch'
|
|
469
|
+
/** Reads the records out of a list response. Defaults to the body itself. */
|
|
470
|
+
readList?: (response: ResourceResponse) => T[]
|
|
471
|
+
/** Reads the record out of a detail or write response. Defaults to the body itself. */
|
|
472
|
+
readOne?: (response: ResourceResponse) => T | null
|
|
473
|
+
}
|
|
474
|
+
```
|
|
475
|
+
|
|
476
|
+
#### `QueryResource`
|
|
477
|
+
|
|
478
|
+
The reads and writes {@link createQueryResource} returns.
|
|
479
|
+
|
|
480
|
+
```typescript
|
|
481
|
+
interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
|
|
482
|
+
/**
|
|
483
|
+
* `useQuery` options for the collection. `viewer` is who the answer is for (the signed-in id,
|
|
484
|
+
* or `'anonymous'`); a page or filter change keeps the rows on screen until the next answer.
|
|
485
|
+
*/
|
|
486
|
+
list(viewer: string, params?: Record<string, unknown>): QueryOptions<T[]>
|
|
487
|
+
/**
|
|
488
|
+
* Options for a collection's whole page (rows plus totals), or a filtered collection path.
|
|
489
|
+
* Reads share this resource's mutation refresh and viewer isolation. `readPage` reads the
|
|
490
|
+
* canonical page response for `path`; row-only `list` reads keep a separate cache entry.
|
|
491
|
+
* Supply `removeFromPage` for opaque page envelopes to remove acknowledged deletions
|
|
492
|
+
* immediately and keep stale list responses from restoring them.
|
|
493
|
+
*/
|
|
494
|
+
listPage<Page>(
|
|
495
|
+
viewer: string,
|
|
496
|
+
params: Record<string, unknown>,
|
|
497
|
+
readPage: (response: ResourceResponse) => Page,
|
|
498
|
+
path?: string,
|
|
499
|
+
removeFromPage?: (page: Page, id: string) => Page,
|
|
500
|
+
): QueryOptions<Page>
|
|
501
|
+
/**
|
|
502
|
+
* `useQuery` options for one record, or null while `id` is not known yet (`useQuery(null)`
|
|
503
|
+
* observes nothing). A missing record resolves to null, not to an error.
|
|
504
|
+
*/
|
|
505
|
+
detail(viewer: string, id: string | null | undefined): QueryOptions<T | null> | null
|
|
506
|
+
/** Creates a record, shows it in the cache and refreshes the lists on screen. */
|
|
507
|
+
create(viewer: string, input: Create): Promise<T>
|
|
508
|
+
/** Updates a record, shows the saved record in the cache and refreshes the lists on screen. */
|
|
509
|
+
update(viewer: string, id: string, input: Update): Promise<T>
|
|
510
|
+
/** Removes a record from detail and tracked row lists, then refreshes those lists. */
|
|
511
|
+
remove(viewer: string, id: string): Promise<void>
|
|
512
|
+
/**
|
|
513
|
+
* Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
|
|
514
|
+
* `DELETE path/id/action` turns it off. Resolves with the saved record, so it is the `commit`
|
|
515
|
+
* of `useOptimisticValue`.
|
|
516
|
+
* The saved detail is published before tracked lists finish refreshing; this promise waits
|
|
517
|
+
* for those refreshes. Render the shared controller's value and let it queue inverse clicks
|
|
518
|
+
* during that interval. A page-local busy guard can drop a click on the newly changed label.
|
|
519
|
+
*/
|
|
520
|
+
toggle(viewer: string, id: string, action: string, on: boolean): Promise<T>
|
|
521
|
+
/** Fetches the lists on screen again, after a change this resource did not make itself. */
|
|
522
|
+
refresh(viewer: string): Promise<void>
|
|
523
|
+
}
|
|
524
|
+
```
|
|
525
|
+
|
|
526
|
+
#### `UseQueryResult`
|
|
527
|
+
|
|
528
|
+
A mounted query's state and its explicit cache and refresh actions. The state
|
|
529
|
+
fields read as plain values at read time (each reads the observer's current
|
|
530
|
+
state signal), so a template binding that calls them re-renders when the
|
|
531
|
+
document changes, and a test can snapshot the object at any moment.
|
|
532
|
+
|
|
533
|
+
```typescript
|
|
534
|
+
interface UseQueryResult<T> extends QueryState<T> {
|
|
535
|
+
/**
|
|
536
|
+
* Publish a saved document to this key and all its observers. Render `data`
|
|
537
|
+
* directly instead of copying it to local state: later cache updates then
|
|
538
|
+
* remain visible. A function receives this key's current cached document,
|
|
539
|
+
* never retained previous-page data. Returning `undefined` leaves the cache
|
|
540
|
+
* unchanged. A disabled (`null`) query does nothing, including not calling an
|
|
541
|
+
* updater. Like React state setters, wrap a function-valued document in an
|
|
542
|
+
* updater. A saved callback stays bound to its original key. The write
|
|
543
|
+
* supersedes older in-flight reads, using the bonded client's `set` contract.
|
|
544
|
+
*/
|
|
545
|
+
setData: (value: T | ((previous: T | undefined) => T | undefined)) => void
|
|
546
|
+
/**
|
|
547
|
+
* Fetch this key again, even when its cached document is fresh. Observers
|
|
548
|
+
* receive the updated state. Resolves with that state, including an error
|
|
549
|
+
* when the request fails; a disabled (`null`) query resolves idle without a
|
|
550
|
+
* request.
|
|
551
|
+
*/
|
|
552
|
+
refetch: () => Promise<QueryState<T>>
|
|
553
|
+
}
|
|
554
|
+
```
|
|
555
|
+
|
|
556
|
+
#### `QueryContentContext`
|
|
557
|
+
|
|
558
|
+
The context a children template receives: the loaded, non-null document, as
|
|
559
|
+
`$implicit` and as the render function's first argument (`a0`).
|
|
560
|
+
|
|
561
|
+
```typescript
|
|
562
|
+
interface QueryContentContext<T> {
|
|
563
|
+
/** The loaded document (never `undefined` or `null`). */
|
|
564
|
+
$implicit: NonNullable<T>
|
|
565
|
+
/** The same document, as the first render argument. */
|
|
566
|
+
a0: NonNullable<T>
|
|
567
|
+
}
|
|
568
|
+
```
|
|
569
|
+
|
|
570
|
+
#### `QueryContentErrorContext`
|
|
571
|
+
|
|
572
|
+
The context an error template receives: the failed read's error value, as
|
|
573
|
+
`$implicit` and as the render function's first argument (`a0`).
|
|
574
|
+
|
|
575
|
+
```typescript
|
|
576
|
+
interface QueryContentErrorContext {
|
|
577
|
+
/** The error the failed read rejected with. */
|
|
578
|
+
$implicit: unknown
|
|
579
|
+
/** The same error, as the first render argument. */
|
|
580
|
+
a0: unknown
|
|
581
|
+
}
|
|
582
|
+
```
|
|
583
|
+
|
|
584
|
+
#### `QueryContentProps`
|
|
585
|
+
|
|
586
|
+
A loaded document owns its controls; absent documents expose only status content.
|
|
587
|
+
|
|
588
|
+
```typescript
|
|
589
|
+
interface QueryContentProps<T> {
|
|
590
|
+
/** State from useQuery, or any compatible query observer. */
|
|
591
|
+
query: Pick<QueryState<T>, 'data' | 'status' | 'error'>
|
|
592
|
+
/** Mounted only with a real document, including false, zero and an empty list. */
|
|
593
|
+
children: TemplateRef<QueryContentContext<T>> | null
|
|
594
|
+
/** Initial idle/loading content. Render a status template, never a fake item or action. */
|
|
595
|
+
pending?: TemplateRef<unknown> | null
|
|
596
|
+
/** Content for a loaded null record. Null is distinct from an unfinished request. */
|
|
597
|
+
missing?: TemplateRef<unknown> | null
|
|
598
|
+
/** A failed initial read. Cached data stays visible if its refresh fails. */
|
|
599
|
+
error?: TemplateRef<QueryContentErrorContext> | null
|
|
600
|
+
}
|
|
601
|
+
```
|
|
602
|
+
|
|
603
|
+
#### `IntentPrefetchProps`
|
|
604
|
+
|
|
605
|
+
The handlers {@link intentPrefetchProps} returns, named after the DOM events
|
|
606
|
+
an Angular template binds (`(pointerenter)`, `(focus)`, `(touchstart)`).
|
|
607
|
+
|
|
608
|
+
```typescript
|
|
609
|
+
interface IntentPrefetchProps {
|
|
610
|
+
/** Warms the document when the pointer arrives. */
|
|
611
|
+
pointerenter: () => void
|
|
612
|
+
/** Warms the document on keyboard focus. */
|
|
613
|
+
focus: () => void
|
|
614
|
+
/** Warms the document when a touch starts. */
|
|
615
|
+
touchstart: () => void
|
|
616
|
+
}
|
|
617
|
+
```
|
|
618
|
+
|
|
619
|
+
### Classes
|
|
620
|
+
|
|
621
|
+
#### `QueryContent`
|
|
622
|
+
|
|
623
|
+
The loaded-data branch receives a non-null document. Pending, failed initial
|
|
624
|
+
reads and missing records never mount that branch, so its actions cannot
|
|
625
|
+
swallow an early click. Cached data remains mounted during refresh, including
|
|
626
|
+
a failed refresh. Status fallbacks belong outside the list or record
|
|
627
|
+
container rendered by `children`, and so does a refresh line; the default
|
|
628
|
+
fallbacks render nothing.
|
|
629
|
+
|
|
630
|
+
The templates receive the render arguments as template context: `children`
|
|
631
|
+
gets the document as `$implicit` and `a0` (`let-data`), `error` gets the
|
|
632
|
+
error value (`let-error`), and `pending`/`missing` render without a context.
|
|
633
|
+
|
|
634
|
+
```typescript
|
|
635
|
+
@Component({
|
|
636
|
+
selector: 'mol-query-content',
|
|
637
|
+
standalone: true,
|
|
638
|
+
template: '<ng-container #outlet></ng-container>',
|
|
639
|
+
inputs: ['query', 'pending', 'missing', 'children', 'error'],
|
|
640
|
+
host: {
|
|
641
|
+
'data-parity-unwrap': '',
|
|
642
|
+
style: 'display: contents',
|
|
643
|
+
},
|
|
644
|
+
})
|
|
645
|
+
export class QueryContent<T = unknown> implements DoCheck, OnChanges {
|
|
646
|
+
/** State from useQuery, or any compatible query observer. */
|
|
647
|
+
query: QueryContentProps<T>['query'] = { data: undefined, status: 'idle', error: undefined }
|
|
648
|
+
/** Mounted only with a real document, including false, zero and an empty list. */
|
|
649
|
+
children: TemplateRef<QueryContentContext<T>> | null = null
|
|
650
|
+
/** Initial idle/loading content. Render a status template, never a fake item or action. */
|
|
651
|
+
pending: TemplateRef<unknown> | null = null
|
|
652
|
+
/** Content for a loaded null record. Null is distinct from an unfinished request. */
|
|
653
|
+
missing: TemplateRef<unknown> | null = null
|
|
654
|
+
/** A failed initial read. Cached data stays visible if its refresh fails. */
|
|
655
|
+
error: TemplateRef<QueryContentErrorContext> | null = null
|
|
656
|
+
|
|
657
|
+
/** Where the chosen branch renders. */
|
|
658
|
+
@ViewChild('outlet', { read: ViewContainerRef, static: true })
|
|
659
|
+
private outlet!: ViewContainerRef
|
|
660
|
+
/** Marks this region for check when the observed document changes. */
|
|
661
|
+
private readonly changeDetector = inject(ChangeDetectorRef)
|
|
662
|
+
/** The observer the reactivity effect is subscribed to (a new prop re-subscribes it). */
|
|
663
|
+
private readonly observer = signal<QueryContentProps<T>['query']>(this.query)
|
|
664
|
+
/** The template currently mounted. */
|
|
665
|
+
private current: TemplateRef<unknown> | null = null
|
|
666
|
+
/** The context object the mounted view reads (updated in place). */
|
|
667
|
+
private readonly context: Record<string, unknown> = {}
|
|
668
|
+
/** The mounted branch view, when a template is showing. */
|
|
669
|
+
private view?: EmbeddedViewRef<unknown>
|
|
670
|
+
|
|
671
|
+
constructor() {
|
|
672
|
+
// A `useQuery` result exposes its state through getters that read the
|
|
673
|
+
// observer's own signals. React re-renders a `QueryContent`'s parent on
|
|
674
|
+
// every state change; Angular only re-checks a view something marked, and
|
|
675
|
+
// the parent's `[query]="query"` binding reads none of those signals. Read
|
|
676
|
+
// them here, in an effect, so a changed document marks this region for
|
|
677
|
+
// check exactly when React would re-render it. A replaced `query` prop
|
|
678
|
+
// re-subscribes the same effect to the new observer.
|
|
679
|
+
effect(() => {
|
|
680
|
+
const query = this.observer()
|
|
681
|
+
void query?.data
|
|
682
|
+
void query?.status
|
|
683
|
+
void query?.error
|
|
684
|
+
untracked(() => {
|
|
685
|
+
this.update()
|
|
686
|
+
this.changeDetector.markForCheck()
|
|
687
|
+
})
|
|
688
|
+
})
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* The branch the current query state shows.
|
|
693
|
+
* @returns The template and its context, or nothing.
|
|
694
|
+
*/
|
|
695
|
+
private branch(): Branch {
|
|
696
|
+
const query = this.query
|
|
697
|
+
if (query?.data === undefined) {
|
|
698
|
+
return query?.status === 'error' && this.error
|
|
699
|
+
? {
|
|
700
|
+
template: this.error,
|
|
701
|
+
context: { $implicit: query.error, a0: query.error },
|
|
702
|
+
}
|
|
703
|
+
: { template: this.pending ?? null, context: {} }
|
|
704
|
+
}
|
|
705
|
+
if (query.data === null) return { template: this.missing ?? null, context: {} }
|
|
706
|
+
return { template: this.children, context: { $implicit: query.data, a0: query.data } }
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
/**
|
|
710
|
+
* Follows a replaced `query` prop: the reactivity effect subscribes to the
|
|
711
|
+
* new observer's own signals on its next run.
|
|
712
|
+
*/
|
|
713
|
+
ngOnChanges(): void {
|
|
714
|
+
this.observer.set(this.query)
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* Mounts the branch the query state shows, and refreshes the mounted view's
|
|
719
|
+
* context when the state changes. Runs on every change-detection pass, so an
|
|
720
|
+
* input set by a host binding is always folded in before this runs.
|
|
721
|
+
*/
|
|
722
|
+
ngDoCheck(): void {
|
|
723
|
+
this.update()
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* Shows the branch the current query state describes: a different template
|
|
728
|
+
* replaces the mounted view, and a changed document (or error) is written into
|
|
729
|
+
* the context the mounted view reads.
|
|
730
|
+
*/
|
|
731
|
+
private update(): void {
|
|
732
|
+
const next = this.branch()
|
|
733
|
+
if (next.template !== this.current) {
|
|
734
|
+
this.view?.destroy()
|
|
735
|
+
this.view = undefined
|
|
736
|
+
this.current = next.template
|
|
737
|
+
if (next.template) this.view = this.outlet.createEmbeddedView(next.template, this.context)
|
|
738
|
+
}
|
|
739
|
+
for (const key of Object.keys(this.context)) {
|
|
740
|
+
if (!(key in next.context)) delete this.context[key]
|
|
741
|
+
}
|
|
742
|
+
Object.assign(this.context, next.context)
|
|
743
|
+
this.view?.markForCheck()
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
```
|
|
747
|
+
|
|
748
|
+
### Functions
|
|
749
|
+
|
|
750
|
+
#### `prefetchQuery(options)`
|
|
751
|
+
|
|
752
|
+
Warms the cache for a document, when the connection can afford it (see
|
|
753
|
+
`shouldPrefetch()` in the core). Safe to call repeatedly: a fresh or
|
|
754
|
+
in-flight document is skipped, and failures are swallowed.
|
|
755
|
+
|
|
756
|
+
```typescript
|
|
757
|
+
function prefetchQuery<T>(options: QueryOptions<T>): void
|
|
758
|
+
```
|
|
759
|
+
|
|
760
|
+
- `options` — Key, fetch, freshness.
|
|
761
|
+
|
|
762
|
+
#### `createQueryResource(config)`
|
|
763
|
+
|
|
764
|
+
Describe one API resource once and get its reads and writes on the shared cache.
|
|
765
|
+
|
|
766
|
+
A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
|
|
767
|
+
re-solve the same problems on every screen: a late answer for the previous page lands
|
|
768
|
+
over the current one, and a list still shows what it showed before a comment was added.
|
|
769
|
+
Here the reads are `useQuery` options (one key per
|
|
770
|
+
viewer, page and filter; the previous rows stay until the next answer) and every write puts
|
|
771
|
+
the server's own record into the cache and fetches the lists on screen again.
|
|
772
|
+
|
|
773
|
+
The factory supplies data operations. Mount a keyed
|
|
774
|
+
control inside `QueryContent` (your framework's query package: `@molecule/app-query-react`,
|
|
775
|
+
`-vue`, …) so it receives a loaded record and stays mounted during refresh.
|
|
776
|
+
For a server-backed toggle, use `useOptimisticValue` from your framework binding
|
|
777
|
+
(`@molecule/app-react`, `@molecule/app-vue`, …), or `OptimisticToggleButton` from its UI
|
|
778
|
+
package (`@molecule/app-ui-react`, …) for a boolean. Pass `toggle` as its
|
|
779
|
+
commit adapter, return the saved flag/count, and render the controller's value for the action
|
|
780
|
+
label too. Do not block clicks while that commit is pending. The resource example in
|
|
781
|
+
`@molecule/app-query-react` composes these APIs; a custom handler must provide the same
|
|
782
|
+
readiness and ordering itself.
|
|
783
|
+
|
|
784
|
+
Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
|
|
785
|
+
and the query provider are whatever the app bonded.
|
|
786
|
+
|
|
787
|
+
```typescript
|
|
788
|
+
function createQueryResource<T, Create = Partial<T>, Update = Partial<T>>(
|
|
789
|
+
config: QueryResourceConfig<T>,
|
|
790
|
+
): QueryResource<T, Create, Update>
|
|
791
|
+
```
|
|
792
|
+
|
|
793
|
+
- `config` — The resource's name, path, HTTP client and response readers.
|
|
794
|
+
|
|
795
|
+
**Returns:** List and detail query options, and create, update, remove, toggle and refresh.
|
|
796
|
+
|
|
797
|
+
#### `usePrefetch()`
|
|
798
|
+
|
|
799
|
+
A stable `prefetch(options)` function for event handlers. Call it in an
|
|
800
|
+
injection context (a component field initializer or constructor); the
|
|
801
|
+
returned function is one object for the component's lifetime.
|
|
802
|
+
|
|
803
|
+
```typescript
|
|
804
|
+
function usePrefetch(): <T>(options: QueryOptions<T>) => void
|
|
805
|
+
```
|
|
806
|
+
|
|
807
|
+
**Returns:** The prefetch function.
|
|
808
|
+
|
|
809
|
+
#### `intentPrefetchProps(options)`
|
|
810
|
+
|
|
811
|
+
Handlers that warm a document at the first sign of intent: the pointer
|
|
812
|
+
arriving, keyboard focus, or a touch starting. Put them on a link's host
|
|
813
|
+
bindings (each property is named after the DOM event it warms on):
|
|
814
|
+
|
|
815
|
+
```typescript
|
|
816
|
+
host: { '(pointerenter)': 'prefetch.pointerenter()', '(focus)': 'prefetch.focus()' }
|
|
817
|
+
```
|
|
818
|
+
|
|
819
|
+
It is a plain function (not a hook), so it works inside `@for` loops too.
|
|
820
|
+
|
|
821
|
+
```typescript
|
|
822
|
+
function intentPrefetchProps<T>(options: QueryOptions<T>): IntentPrefetchProps
|
|
823
|
+
```
|
|
824
|
+
|
|
825
|
+
- `options` — Key, fetch, freshness.
|
|
826
|
+
|
|
827
|
+
**Returns:** The handlers.
|
|
828
|
+
|
|
829
|
+
#### `useQuery(options)`
|
|
830
|
+
|
|
831
|
+
The document for the options' key, kept current: cached data is read on the
|
|
832
|
+
very first render (so a warmed page never flashes a loading state), a stale
|
|
833
|
+
or missing document is fetched, and every change re-renders the template that
|
|
834
|
+
reads the result. Pass `null` to observe nothing. A key change resets to that
|
|
835
|
+
key's state; the hook never hands a caller another key's document — unless
|
|
836
|
+
the caller opts into {@link QueryOptions.keepPreviousData}, and then only
|
|
837
|
+
within one {@link QueryOptions.principal}.
|
|
838
|
+
|
|
839
|
+
The request is stable across template refreshes — a parent state change
|
|
840
|
+
neither restarts it nor cancels it, so a response that arrives after one still
|
|
841
|
+
lands. It is aborted only when the key changes or the component is destroyed
|
|
842
|
+
(the `signal` given to `options.fetch`). Use this instead of a hand-written
|
|
843
|
+
effect + `fetch`: an effect whose cleanup sets a `cancelled` flag, and whose
|
|
844
|
+
tracked dependencies include a function rebuilt each run, cancels its own
|
|
845
|
+
request on every run and then skips the refetch.
|
|
846
|
+
An explicit `refetch()` is an awaited cache fetch; it can finish after the
|
|
847
|
+
observer is destroyed, like an explicit `client.fetch(options)` caller.
|
|
848
|
+
|
|
849
|
+
For a LIST, put the route's page, filter and selected view in the key and
|
|
850
|
+
pass `keepPreviousData` with a `principal`: a Next/Previous or filter change
|
|
851
|
+
then keeps the rows already on screen until the new page answers, instead of
|
|
852
|
+
rendering a loading state over an empty list. The key names everything the
|
|
853
|
+
answer depends on, and the app's HTTP client sends the session, so a list the
|
|
854
|
+
server can filter or personalize per viewer puts the viewer in its key and
|
|
855
|
+
passes the same value as `principal` (`'anonymous'` when signed out): an
|
|
856
|
+
account switch then drops the previous account's document immediately. Only
|
|
857
|
+
an endpoint that answers every viewer the same takes a viewer-free key with
|
|
858
|
+
`principal: 'public'`.
|
|
859
|
+
|
|
860
|
+
For custom mutation handlers, `setData(saved)` publishes the server's response to this
|
|
861
|
+
key and every observer. Use `setData(current => next)` for a local cache update. Render
|
|
862
|
+
`data` directly; a component-local copy stops observing later server responses. Prefer
|
|
863
|
+
`createQueryResource` when the API's reads and writes can share one resource definition.
|
|
864
|
+
Mount record-dependent actions inside `QueryContent` (or an explicit non-null data branch),
|
|
865
|
+
so a visible action cannot return early because its initial record is still missing.
|
|
866
|
+
Keep loaded actions mounted during refreshes. Server-backed toggles use
|
|
867
|
+
`OptimisticToggleButton` from `@molecule/app-ui-angular` (or `useOptimisticValue`
|
|
868
|
+
from `@molecule/app-angular` in a control that is re-created per record) to keep
|
|
869
|
+
their displayed label and queued clicks on the same state while a save finishes.
|
|
870
|
+
|
|
871
|
+
```typescript
|
|
872
|
+
function useQuery<T>(options: QueryOptionsSource<T>): UseQueryResult<T>
|
|
873
|
+
```
|
|
874
|
+
|
|
875
|
+
- `options` — Key, fetch, freshness, and optionally `principal` with `keepPreviousData`; or `null`; or a signal of either (the options a component recomputes on its own state — every change is followed on the same instance).
|
|
876
|
+
|
|
877
|
+
**Returns:** The document's state, `setData()` and `refetch()`. `isPreviousData` is `true` while `data` is the previous key's document for the same principal.
|
|
878
|
+
|
|
879
|
+
## Injection Notes
|
|
880
|
+
|
|
881
|
+
### Requirements
|
|
882
|
+
|
|
883
|
+
Peer dependencies:
|
|
884
|
+
|
|
885
|
+
- `@angular/common` ^22.0.0
|
|
886
|
+
- `@angular/core` ^22.0.0
|
|
887
|
+
- `@angular/platform-browser` ^22.0.0
|
|
888
|
+
- `@molecule/app-query` ^1.2.0
|
|
889
|
+
|
|
890
|
+
### Runtime Dependencies
|
|
891
|
+
|
|
892
|
+
- `@angular/common`
|
|
893
|
+
- `@angular/core`
|
|
894
|
+
- `@angular/platform-browser`
|
|
895
|
+
- `@molecule/app-query`
|
|
896
|
+
|
|
897
|
+
- **`useQuery` reads the cache synchronously on the first render.** A
|
|
898
|
+
document prefetched from a hovered link, or seeded with `client.set()`
|
|
899
|
+
from a server-rendered JSON island, renders at once — no spinner, no
|
|
900
|
+
layout shift. Render loading from `status === 'idle' || status === 'loading'`;
|
|
901
|
+
`undefined` data can also accompany a completed error. A completed `null`
|
|
902
|
+
response is missing, not pending. The detail example treats only HTTP 404
|
|
903
|
+
or a successful null response as missing; other errors stay load failures.
|
|
904
|
+
The app's bonded HTTP client rejects non-2xx responses. Native `fetch`
|
|
905
|
+
resolves them, so a custom fetcher must check `response.ok` before JSON.
|
|
906
|
+
- **Mount a detail region and its actions only after its initial document arrives.**
|
|
907
|
+
A visible container is not a loaded document: a caller may wait for that container and
|
|
908
|
+
read its text once, or click its button, while `data` is still undefined. Put the loading
|
|
909
|
+
message outside the detail region, as in `PackagePage` above. Keep record-dependent
|
|
910
|
+
controls absent or natively disabled until the record exists; returning early inside
|
|
911
|
+
an enabled click handler loses that click. `client.set()` protects a cache mutation
|
|
912
|
+
from an older read, but cannot recover a click whose handler never sent the mutation.
|
|
913
|
+
- **The key is the identity.** Building the options inline inside a
|
|
914
|
+
`computed` is fine; the hook resubscribes only when the key's value
|
|
915
|
+
changes, not when the `fetch` closure does.
|
|
916
|
+
- **A key change normally resets to the new key's state.** For a list's own
|
|
917
|
+
page/filter/view change, opt into `keepPreviousData` with a `principal`;
|
|
918
|
+
`isPreviousData` tells you the rows on screen belong to the key you just
|
|
919
|
+
left. A completed response (including an empty list) replaces them, and a
|
|
920
|
+
changed principal drops them, so an account switch never shows the previous
|
|
921
|
+
account's rows. Do not emulate this with a component-local copy of the
|
|
922
|
+
query data — that mirror is what serves stale rows under a new page, or
|
|
923
|
+
blanks the list on a re-render.
|
|
924
|
+
- **The key names the viewer whenever the answer can depend on it.** The
|
|
925
|
+
app's HTTP client sends the session, so the server may filter or
|
|
926
|
+
personalize even a list that guests can see (a `favorited` or `following`
|
|
927
|
+
flag), and the cache serves a key's document to whoever observes it,
|
|
928
|
+
across sign-in and sign-out. Key such a list on the viewer
|
|
929
|
+
(`user ? String(user.id) : 'anonymous'`), pass the same value as
|
|
930
|
+
`principal`, and pass `null` while the session is still being restored
|
|
931
|
+
(`status === 'loading'`; the HTTP client holds the request until then
|
|
932
|
+
anyway), so restoring a session never swaps a key that already rendered
|
|
933
|
+
rows. A viewer-free key with `principal: 'public'` is only for an endpoint
|
|
934
|
+
that answers every viewer the same. A protected route view also passes
|
|
935
|
+
`null` while it cannot load yet.
|
|
936
|
+
- **Render loading, empty and error status outside the item list**, and never
|
|
937
|
+
give a placeholder the item's own class or element shape: a list read by
|
|
938
|
+
the item class (or by `:first-child`) must contain only real items. An
|
|
939
|
+
empty array is a loaded empty state, not a missing response; render it
|
|
940
|
+
only when `isPreviousData` is not set, because a retained document belongs
|
|
941
|
+
to the key you just left.
|
|
942
|
+
- `intentPrefetchProps` returns three handlers named after the DOM events an
|
|
943
|
+
Angular template binds (`pointerenter`, `focus`, `touchstart`). It is a
|
|
944
|
+
plain function (not a hook), so it works inside `@for` too.
|
|
945
|
+
- Prefetching respects the browser's data-saver setting and skips 2G
|
|
946
|
+
connections (`shouldPrefetch()` in the core) — do not bypass that for
|
|
947
|
+
"important" links; the person can still click.
|
|
948
|
+
- **Refresh a mounted document with `query.refetch()`.** It fetches even a fresh cache
|
|
949
|
+
entry and updates every observer of that key. After a mutation whose response is not the
|
|
950
|
+
whole document, `await query.refetch()` reloads the displayed list. It resolves with the
|
|
951
|
+
resulting state (including `status: 'error'` on failure); a disabled query stays idle.
|
|
952
|
+
Prefer `client.set(key, response)` when the mutation already returned the whole document.
|
|
953
|
+
- Errors are not thrown from the hook; read `status === 'error'` and
|
|
954
|
+
`error`. `client.invalidate()` does NOT refetch a mounted page — it only
|
|
955
|
+
marks documents stale, so the page keeps its error (or its old document)
|
|
956
|
+
until the app retries with `client.fetch(options)` or the page subscribes
|
|
957
|
+
again (a key change or a re-mount).
|
|
958
|
+
- After a mutation, `client.set(key, response)` paints the server's own
|
|
959
|
+
answer at once and supersedes an older fetch already in flight for that
|
|
960
|
+
key, so its response cannot undo the mutation. An existing `fetch()` caller
|
|
961
|
+
still settles independently of the cache write; read `client.get(key)` for the newest document.
|
|
962
|
+
`client.invalidate(prefix)` marks the affected reads stale for their next
|
|
963
|
+
mount. Which key and which scope is the app's decision: the cache does not
|
|
964
|
+
infer it from auth or form state.
|
|
965
|
+
- The result's state fields are signals read through plain properties
|
|
966
|
+
(`query.data`, `query.isPreviousData`), so a template binding that reads
|
|
967
|
+
them re-renders when the document changes, and the object can be handed to
|
|
968
|
+
`QueryContent`'s `query` input unchanged.
|
|
969
|
+
|
|
970
|
+
Render resource-dependent lists and controls through {@link QueryContent}. Its children
|
|
971
|
+
template receives only loaded, non-null data; loading and error content never mount item
|
|
972
|
+
actions. It renders cached content during refresh and treats an empty list, false and zero
|
|
973
|
+
as data. Put the list, or the record's own container (its card, header or profile block),
|
|
974
|
+
inside the children template and every status line (loading, error, `isFetching` refresh)
|
|
975
|
+
beside it, never inside it: a reader that finds the container and reads its paragraph must
|
|
976
|
+
read the record, not "Loading…".
|
|
977
|
+
|
|
978
|
+
Keep every resource identity in the query key. A boundary cannot correct a query that supplies
|
|
979
|
+
another record's cached data. For a list, map real rows inside the children template; never
|
|
980
|
+
style a status placeholder as a row.
|