@mmstack/resource 21.3.2 → 21.4.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 +92 -2
- package/fesm2022/mmstack-resource.mjs +175 -56
- package/fesm2022/mmstack-resource.mjs.map +1 -1
- package/package.json +2 -2
- package/types/mmstack-resource.d.ts +74 -18
package/README.md
CHANGED
|
@@ -21,6 +21,9 @@ It's designed to be opt-in feature by feature: starting with `queryResource()` a
|
|
|
21
21
|
- [`manualQueryResource`](#manualqueryresource)
|
|
22
22
|
- [Caching](#caching)
|
|
23
23
|
- [Circuit breakers](#circuit-breakers)
|
|
24
|
+
- [Transitions & Suspense](#transitions--suspense)
|
|
25
|
+
- [Pausing a resource](#pausing-a-resource)
|
|
26
|
+
- [Default options (`provideResourceOptions`)](#default-options-provideresourceoptions)
|
|
24
27
|
- [Composition (retry / refresh / keepPrevious)](#composition-retry--refresh--keepprevious)
|
|
25
28
|
- [Recipes](#recipes)
|
|
26
29
|
|
|
@@ -177,12 +180,12 @@ queryResource(() => ({
|
|
|
177
180
|
|
|
178
181
|
```ts
|
|
179
182
|
queryResource<TResult, TRaw = TResult>(
|
|
180
|
-
request: () => HttpResourceRequest | string | undefined,
|
|
183
|
+
request: (ctx: RequestContext) => HttpResourceRequest | string | undefined | typeof PAUSED,
|
|
181
184
|
options?: QueryResourceOptions<TResult, TRaw>,
|
|
182
185
|
): QueryResourceRef<TResult>
|
|
183
186
|
```
|
|
184
187
|
|
|
185
|
-
`request` is a reactive function. Whenever it returns a new value, a new request is made; returning `undefined` disables the resource until the function returns something again.
|
|
188
|
+
`request` is a reactive function. Whenever it returns a new value, a new request is made; returning `undefined` **disables** the resource until the function returns something again. It receives a `RequestContext` whose `paused` token it can return to **pause** instead — see [pausing a resource](#pausing-a-resource).
|
|
186
189
|
|
|
187
190
|
### Options
|
|
188
191
|
|
|
@@ -196,7 +199,9 @@ queryResource<TResult, TRaw = TResult>(
|
|
|
196
199
|
| `circuitBreaker` | `true \| CircuitBreaker \| { threshold?, timeout?, … }` | off | See [circuit breakers](#circuit-breakers). |
|
|
197
200
|
| `cache` | `ResourceCacheOptions` | off | Enables caching for this resource. See [caching](#caching). |
|
|
198
201
|
| `triggerOnSameRequest` | `boolean` | `false` | Re-run even if the request object equals the previous one. Use sparingly. |
|
|
202
|
+
| `register` | `boolean \| { suspends?: boolean }` | `false` | Auto-register into the nearest transition scope. See [transitions & Suspense](#transitions--suspense). |
|
|
199
203
|
| `equal` | `ValueEqualityFn<TResult>` | `Object.is` | Custom equality for the result value (forwarded to `httpResource`). |
|
|
204
|
+
| `equalRequest` | `(a, b) => boolean` | structural | Custom equality for the **request** object (controls dedup / refetch). Defaults to a deep structural compare. |
|
|
200
205
|
| `injector` | `Injector` | `inject(Injector)` | Use this injector for cache/circuit-breaker resolution. Required if calling outside an injection context. |
|
|
201
206
|
| `parse` | `(raw: TRaw) => TResult` | identity | Transform the raw HTTP response. Does not affect cache keys. |
|
|
202
207
|
|
|
@@ -270,6 +275,16 @@ mutationResource(request, { queue: true });
|
|
|
270
275
|
|
|
271
276
|
Queued mutations sit in a signal-backed queue and execute one at a time. The queue **persists across resource-disabled states** — if the circuit breaker opens or the network drops, queued mutations stay pending and run when the resource recovers. This is intentional for resilience (think "POST goes out when we're back online"), but it does mean a queued mutation can fire long after the user triggered it. Don't enable `queue` if that's surprising in your UX.
|
|
272
277
|
|
|
278
|
+
### Re-firing with an identical body (`triggerOnSameRequest`)
|
|
279
|
+
|
|
280
|
+
A mutation is an imperative command, so by default an identical `mutate(body)` while one is in flight is **deduplicated** (double-click protection). When a repeat with the same body _must_ fire — e.g. a "resend" button — set `triggerOnSameRequest: true`, and every `mutate()` fires regardless of whether the body changed.
|
|
281
|
+
|
|
282
|
+
```typescript
|
|
283
|
+
mutationResource(request, { triggerOnSameRequest: true });
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
A mutation also honours the `register` option — but it registers the **mutation ref itself** into the transition scope (its internal query is never registered), so a `<mm-suspense>`/transition reacts to the mutation's own `pending` state. See [transitions & Suspense](#transitions--suspense).
|
|
287
|
+
|
|
273
288
|
### Return shape (`MutationResourceRef<T, TMutation>`)
|
|
274
289
|
|
|
275
290
|
| Member | Type | Notes |
|
|
@@ -410,6 +425,81 @@ authService.refreshToken().subscribe(() => {
|
|
|
410
425
|
|
|
411
426
|
`hardReset()` is also useful for testing — it gives you a "back to factory state" handle without reconstructing the breaker.
|
|
412
427
|
|
|
428
|
+
## Transitions & Suspense
|
|
429
|
+
|
|
430
|
+
Resources plug into `@mmstack/primitives`' [transition scope](https://www.npmjs.com/package/@mmstack/primitives#concurrency--transitions) — the machinery behind Suspense boundaries and route transitions. Set `register` and the resource adds itself to the nearest scope (and removes itself on destroy), so a `<mm-suspense>` boundary or a `<mm-transition-outlet>` can coordinate its loading state:
|
|
431
|
+
|
|
432
|
+
The boundary provides the scope, so the resource has to register from **inside** it — i.e. the data-owning component sits within the `<mm-suspense>` tags (registration resolves the scope up the injector tree). A query declared on the same component that _renders_ the boundary is above it and won't be captured.
|
|
433
|
+
|
|
434
|
+
```typescript
|
|
435
|
+
import { Component, input } from '@angular/core';
|
|
436
|
+
import { SuspenseBoundary } from '@mmstack/primitives';
|
|
437
|
+
import { queryResource } from '@mmstack/resource';
|
|
438
|
+
|
|
439
|
+
@Component({ selector: 'user-profile', template: `{{ user.value()?.name }}` })
|
|
440
|
+
class UserProfile {
|
|
441
|
+
readonly id = input.required<string>();
|
|
442
|
+
// `register: { suspends: true }` registers into the nearest scope (the
|
|
443
|
+
// <mm-suspense> above) and blocks its first paint until a value lands.
|
|
444
|
+
readonly user = queryResource<User>(() => `/api/users/${this.id()}`, {
|
|
445
|
+
register: { suspends: true },
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
@Component({
|
|
450
|
+
selector: 'user-page',
|
|
451
|
+
imports: [SuspenseBoundary, UserProfile],
|
|
452
|
+
template: `
|
|
453
|
+
<mm-suspense>
|
|
454
|
+
<span placeholder>Loading…</span>
|
|
455
|
+
<user-profile [id]="id()" />
|
|
456
|
+
</mm-suspense>
|
|
457
|
+
`,
|
|
458
|
+
})
|
|
459
|
+
class UserPage {
|
|
460
|
+
readonly id = input.required<string>();
|
|
461
|
+
}
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
- `register: true` (or `{ suspends: false }`) — register for the **pending indicator + hold-stale**; does _not_ block first paint. The right choice for in-region data: the boundary shows the held value with `aria-busy`, not a placeholder.
|
|
465
|
+
- `register: { suspends: true }` — register as **suspending**: the boundary holds its placeholder until this resource has a value (full Suspense).
|
|
466
|
+
- `false` / omitted — don't register.
|
|
467
|
+
|
|
468
|
+
Combine with `keepPrevious: true` so reloads hold the last value instead of flashing empty — then a `<mm-suspense>` shows the placeholder only on the genuine first load, and `startTransition` (from `@mmstack/primitives`) can reveal a multi-resource update in one frame. For navigation, `@mmstack/router-core`'s `<mm-transition-outlet>` keeps the current route on screen until the incoming route's registered resources settle.
|
|
469
|
+
|
|
470
|
+
## Pausing a resource
|
|
471
|
+
|
|
472
|
+
The request fn can return `ctx.paused` (the `PAUSED` token) to **pause** the resource: it holds its current value and last request, stops polling, and does **not** refetch on resume unless the request changed. This is distinct from returning `undefined` (which _disables_ — a disabled resource may refetch when re-enabled; a paused one resumes exactly where it left off). It pairs with keep-alive (`MmActivity` / `injectPaused`) so a hidden tab's queries go quiet without losing their data:
|
|
473
|
+
|
|
474
|
+
```typescript
|
|
475
|
+
import { injectPaused } from '@mmstack/primitives';
|
|
476
|
+
|
|
477
|
+
class Panel {
|
|
478
|
+
private readonly paused = injectPaused(); // true while the tab is hidden by *mmActivity
|
|
479
|
+
|
|
480
|
+
readonly data = queryResource<Data>((ctx) =>
|
|
481
|
+
this.paused() ? ctx.paused : `/api/data/${this.id()}`,
|
|
482
|
+
);
|
|
483
|
+
}
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
## Default options (`provideResourceOptions`)
|
|
487
|
+
|
|
488
|
+
Common options (`register`, `retry`, `circuitBreaker`, `triggerOnSameRequest`) can be defaulted app-wide, with a three-layer precedence — **per-call > type-specific provider > common provider**:
|
|
489
|
+
|
|
490
|
+
```typescript
|
|
491
|
+
providers: [
|
|
492
|
+
// Layer 1 — applies to every resource kind.
|
|
493
|
+
provideResourceOptions({ retry: { max: 2 }, register: true }),
|
|
494
|
+
// Layer 2 — queries only (inherits + overrides layer 1).
|
|
495
|
+
provideQueryResourceOptions({ circuitBreaker: true }),
|
|
496
|
+
// Layer 2 — mutations only.
|
|
497
|
+
provideMutationResourceOptions({ register: false }),
|
|
498
|
+
];
|
|
499
|
+
```
|
|
500
|
+
|
|
501
|
+
Each accepts a value or a factory (`() => options`). A per-call option always wins — including opting out of a provider default with `register: false` — so you can make "all queries participate in transitions" the default and turn it off for the odd one.
|
|
502
|
+
|
|
413
503
|
## Composition (retry / refresh / keepPrevious)
|
|
414
504
|
|
|
415
505
|
The wrappers stack in a fixed order inside `queryResource`:
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { HttpHeaders, HttpResponse, HttpParams, HttpContextToken, HttpContext, httpResource, HttpClient } from '@angular/common/http';
|
|
2
2
|
import * as i0 from '@angular/core';
|
|
3
|
-
import { isDevMode, untracked, computed, InjectionToken, inject, signal, effect, Injector,
|
|
4
|
-
import { mutable, toWritable, sensor, nestedEffect } from '@mmstack/primitives';
|
|
3
|
+
import { isDevMode, untracked, computed, InjectionToken, inject, signal, effect, Injector, Injectable, runInInjectionContext, DestroyRef, linkedSignal } from '@angular/core';
|
|
4
|
+
import { mutable, toWritable, keepPrevious, sensor, injectTransitionScope, nestedEffect } from '@mmstack/primitives';
|
|
5
5
|
import { of, tap, map, finalize, shareReplay, interval, firstValueFrom, catchError, combineLatestWith, filter } from 'rxjs';
|
|
6
6
|
import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
|
|
7
7
|
|
|
@@ -654,17 +654,13 @@ function hash(...args) {
|
|
|
654
654
|
}
|
|
655
655
|
|
|
656
656
|
function normalizeParams(params) {
|
|
657
|
-
const p = params instanceof HttpParams
|
|
658
|
-
? params
|
|
659
|
-
: new HttpParams({ fromObject: params });
|
|
657
|
+
const p = params instanceof HttpParams ? params : new HttpParams({ fromObject: params });
|
|
660
658
|
return p
|
|
661
659
|
.keys()
|
|
662
660
|
.toSorted()
|
|
663
661
|
.map((key) => {
|
|
664
662
|
const encodedKey = encodeURIComponent(key);
|
|
665
|
-
return (p.getAll(key) ?? [])
|
|
666
|
-
.map((v) => `${encodedKey}=${encodeURIComponent(v)}`)
|
|
667
|
-
.join('&');
|
|
663
|
+
return (p.getAll(key) ?? []).map((v) => `${encodedKey}=${encodeURIComponent(v)}`).join('&');
|
|
668
664
|
})
|
|
669
665
|
.join('&');
|
|
670
666
|
}
|
|
@@ -684,8 +680,7 @@ function hashBody(body) {
|
|
|
684
680
|
entries.sort(([ak, av], [bk, bv]) => ak.localeCompare(bk) || av.localeCompare(bv));
|
|
685
681
|
return `FormData:${entries.map(([k, v]) => `${k}=${v}`).join('&')}`;
|
|
686
682
|
}
|
|
687
|
-
if (typeof URLSearchParams !== 'undefined' &&
|
|
688
|
-
body instanceof URLSearchParams) {
|
|
683
|
+
if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) {
|
|
689
684
|
const sp = new URLSearchParams(body);
|
|
690
685
|
sp.sort();
|
|
691
686
|
return `URLSearchParams:${sp.toString()}`;
|
|
@@ -1355,49 +1350,37 @@ function hasSlowConnection() {
|
|
|
1355
1350
|
return false;
|
|
1356
1351
|
}
|
|
1357
1352
|
|
|
1358
|
-
function persist(src, equal) {
|
|
1359
|
-
// linkedSignal allows us to access previous source value
|
|
1360
|
-
const persisted = linkedSignal({ ...(ngDevMode ? { debugName: "persisted" } : /* istanbul ignore next */ {}), source: () => src(),
|
|
1361
|
-
computation: (next, prev) => {
|
|
1362
|
-
if (next === undefined && prev !== undefined)
|
|
1363
|
-
return prev.value;
|
|
1364
|
-
return next;
|
|
1365
|
-
},
|
|
1366
|
-
equal });
|
|
1367
|
-
// if original value was WritableSignal then override linkedSignal methods to original...angular uses linkedSignal under the hood in ResourceImpl, this applies to that.
|
|
1368
|
-
if ('set' in src) {
|
|
1369
|
-
persisted.set = src.set;
|
|
1370
|
-
persisted.update = src.update;
|
|
1371
|
-
persisted.asReadonly = src.asReadonly;
|
|
1372
|
-
}
|
|
1373
|
-
return persisted;
|
|
1374
|
-
}
|
|
1375
1353
|
function persistResourceValues(resource, shouldPersist = false, equal) {
|
|
1376
1354
|
if (!shouldPersist)
|
|
1377
1355
|
return resource;
|
|
1378
1356
|
return {
|
|
1379
1357
|
...resource,
|
|
1380
|
-
statusCode:
|
|
1381
|
-
headers:
|
|
1382
|
-
value:
|
|
1358
|
+
statusCode: keepPrevious(resource.statusCode),
|
|
1359
|
+
headers: keepPrevious(resource.headers),
|
|
1360
|
+
value: keepPrevious(resource.value, { equal }),
|
|
1383
1361
|
};
|
|
1384
1362
|
}
|
|
1385
1363
|
|
|
1386
|
-
// refresh resource every n miliseconds or don't refresh if undefined provided. 0 also excluded, due to it not being a valid usecase
|
|
1387
|
-
function refresh(resource, destroyRef, refresh) {
|
|
1364
|
+
// refresh resource every n miliseconds or don't refresh if undefined provided. 0 also excluded, due to it not being a valid usecase.
|
|
1365
|
+
function refresh(resource, destroyRef, refresh, inactive) {
|
|
1388
1366
|
if (!refresh)
|
|
1389
1367
|
return resource; // no refresh requested
|
|
1368
|
+
const tick = () => {
|
|
1369
|
+
if (inactive?.())
|
|
1370
|
+
return; // disabled / paused → skip the poll
|
|
1371
|
+
resource.reload();
|
|
1372
|
+
};
|
|
1390
1373
|
// we can use RxJs here as reloading the resource will always be a side effect & as such does not impact the reactive graph in any way.
|
|
1391
1374
|
let sub = interval(refresh)
|
|
1392
1375
|
.pipe(takeUntilDestroyed(destroyRef))
|
|
1393
|
-
.subscribe(
|
|
1376
|
+
.subscribe(tick);
|
|
1394
1377
|
const reload = () => {
|
|
1395
1378
|
sub.unsubscribe(); // do not conflict with manual reload
|
|
1396
1379
|
const hasReloaded = resource.reload();
|
|
1397
1380
|
// resubscribe after manual reload
|
|
1398
1381
|
sub = interval(refresh)
|
|
1399
1382
|
.pipe(takeUntilDestroyed(destroyRef))
|
|
1400
|
-
.subscribe(
|
|
1383
|
+
.subscribe(tick);
|
|
1401
1384
|
return hasReloaded;
|
|
1402
1385
|
};
|
|
1403
1386
|
return {
|
|
@@ -1483,7 +1466,72 @@ function toResourceObject(res) {
|
|
|
1483
1466
|
};
|
|
1484
1467
|
}
|
|
1485
1468
|
|
|
1486
|
-
|
|
1469
|
+
const RESOURCE_OPTIONS = new InjectionToken('@mmstack/resource:resource-options', { factory: () => ({}) });
|
|
1470
|
+
function asProvider(token, valueOrFn) {
|
|
1471
|
+
return typeof valueOrFn === 'function'
|
|
1472
|
+
? { provide: token, useFactory: valueOrFn }
|
|
1473
|
+
: { provide: token, useValue: valueOrFn };
|
|
1474
|
+
}
|
|
1475
|
+
/** Layer 1: defaults that apply to ALL resource kinds. Type-specific providers inherit + override these. */
|
|
1476
|
+
function provideResourceOptions(valueOrFn) {
|
|
1477
|
+
return asProvider(RESOURCE_OPTIONS, valueOrFn);
|
|
1478
|
+
}
|
|
1479
|
+
function injectResourceOptions(injector) {
|
|
1480
|
+
return injector ? injector.get(RESOURCE_OPTIONS) : inject(RESOURCE_OPTIONS);
|
|
1481
|
+
}
|
|
1482
|
+
/** Shared helper for the type-specific providers (query/mutation), so precedence is identical. */
|
|
1483
|
+
function provideTypedResourceOptions(token, valueOrFn) {
|
|
1484
|
+
return asProvider(token, valueOrFn);
|
|
1485
|
+
}
|
|
1486
|
+
/**
|
|
1487
|
+
* Applies a resolved `register` option to a freshly-created resource — adds it to the nearest
|
|
1488
|
+
* transition scope and removes it on destroy. Runs in the resource's injection context (or the
|
|
1489
|
+
* provided `injector`), since registration needs `TRANSITION_SCOPE` + `DestroyRef`.
|
|
1490
|
+
*/
|
|
1491
|
+
function applyResourceRegistration(ref, register, injector) {
|
|
1492
|
+
if (!register)
|
|
1493
|
+
return;
|
|
1494
|
+
const opt = register === true ? { suspends: false } : register;
|
|
1495
|
+
const run = injector
|
|
1496
|
+
? (fn) => runInInjectionContext(injector, fn)
|
|
1497
|
+
: (fn) => fn();
|
|
1498
|
+
run(() => {
|
|
1499
|
+
const scope = injectTransitionScope();
|
|
1500
|
+
const destroyRef = inject(DestroyRef);
|
|
1501
|
+
scope.add(ref, opt);
|
|
1502
|
+
destroyRef.onDestroy(() => scope.remove(ref));
|
|
1503
|
+
});
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
const QUERY_RESOURCE_OPTIONS = new InjectionToken('@mmstack/resource:query-resource-options', { factory: () => ({}) });
|
|
1507
|
+
/**
|
|
1508
|
+
* Layer 2 (query): default options for every `queryResource`, inheriting + overriding the
|
|
1509
|
+
* common defaults from `provideResourceOptions`. Per-call options override these in turn.
|
|
1510
|
+
*/
|
|
1511
|
+
function provideQueryResourceOptions(valueOrFn) {
|
|
1512
|
+
return provideTypedResourceOptions(QUERY_RESOURCE_OPTIONS, valueOrFn);
|
|
1513
|
+
}
|
|
1514
|
+
function injectQueryResourceOptions(injector) {
|
|
1515
|
+
return injector
|
|
1516
|
+
? injector.get(QUERY_RESOURCE_OPTIONS)
|
|
1517
|
+
: inject(QUERY_RESOURCE_OPTIONS);
|
|
1518
|
+
}
|
|
1519
|
+
/**
|
|
1520
|
+
* Returned from a resource's request fn to PAUSE it: the resource holds its current value and last
|
|
1521
|
+
* request (so it does not refetch on resume), and stops background work (no polling, no refetch
|
|
1522
|
+
* while paused). Distinct from returning `undefined` (DISABLE), which drops the request — a
|
|
1523
|
+
* disabled resource may refetch when re-enabled, a paused one resumes exactly where it left off.
|
|
1524
|
+
*
|
|
1525
|
+
* The request fn receives a {@link RequestContext} and can just return `ctx.paused`.
|
|
1526
|
+
*/
|
|
1527
|
+
const PAUSED = Symbol('@mmstack/resource:paused');
|
|
1528
|
+
function queryResource(request, options0) {
|
|
1529
|
+
// Two-layer option injection: per-call > provideQueryResourceOptions > provideResourceOptions.
|
|
1530
|
+
const options = {
|
|
1531
|
+
...injectResourceOptions(options0?.injector),
|
|
1532
|
+
...injectQueryResourceOptions(options0?.injector),
|
|
1533
|
+
...options0,
|
|
1534
|
+
};
|
|
1487
1535
|
const cache = injectQueryCache(options?.injector);
|
|
1488
1536
|
const destroyRef = options?.injector
|
|
1489
1537
|
? options.injector.get(DestroyRef)
|
|
@@ -1494,27 +1542,47 @@ function queryResource(request, options) {
|
|
|
1494
1542
|
const networkAvailable = injectNetworkStatus();
|
|
1495
1543
|
const eq = options?.triggerOnSameRequest
|
|
1496
1544
|
? undefined
|
|
1497
|
-
:
|
|
1498
|
-
const
|
|
1545
|
+
: (options?.equalRequest ?? createEqualRequest());
|
|
1546
|
+
const requestCtx = { paused: PAUSED };
|
|
1547
|
+
const rawResult = computed(() => request(requestCtx), ...(ngDevMode ? [{ debugName: "rawResult" }] : /* istanbul ignore next */ []));
|
|
1548
|
+
const paused = computed(() => rawResult() === PAUSED, ...(ngDevMode ? [{ debugName: "paused" }] : /* istanbul ignore next */ []));
|
|
1549
|
+
const rawRequest = computed(() => {
|
|
1550
|
+
const r = rawResult();
|
|
1551
|
+
return r === PAUSED ? undefined : (r ?? undefined);
|
|
1552
|
+
}, ...(ngDevMode ? [{ debugName: "rawRequest" }] : /* istanbul ignore next */ []));
|
|
1499
1553
|
const disabledReason = computed(() => {
|
|
1500
1554
|
if (!networkAvailable())
|
|
1501
1555
|
return 'offline';
|
|
1502
1556
|
if (cb.isOpen())
|
|
1503
1557
|
return 'circuit-open';
|
|
1558
|
+
// PAUSED makes rawRequest undefined, so it reports 'no-request' here (and skips polling),
|
|
1559
|
+
// while stableRequest below HOLDS the last request so the value is kept (no refetch on resume).
|
|
1504
1560
|
if (!rawRequest())
|
|
1505
1561
|
return 'no-request';
|
|
1506
1562
|
return null;
|
|
1507
1563
|
}, ...(ngDevMode ? [{ debugName: "disabledReason" }] : /* istanbul ignore next */ []));
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1564
|
+
// While PAUSED, hold the previous request so httpResource sees no change — it keeps its value and
|
|
1565
|
+
// does NOT refetch. On resume the request is re-evaluated, so it refetches only if it changed.
|
|
1566
|
+
const heldRequest = linkedSignal({ ...(ngDevMode ? { debugName: "heldRequest" } : /* istanbul ignore next */ {}), source: () => {
|
|
1567
|
+
if (paused())
|
|
1568
|
+
return { req: undefined, held: true };
|
|
1569
|
+
if (disabledReason() !== null)
|
|
1570
|
+
return { req: undefined, held: false };
|
|
1571
|
+
const req = rawRequest();
|
|
1572
|
+
if (!req)
|
|
1573
|
+
return { req: undefined, held: false };
|
|
1574
|
+
if (typeof req === 'string')
|
|
1575
|
+
return { req: { method: 'GET', url: req }, held: false };
|
|
1576
|
+
return { req, held: false };
|
|
1577
|
+
},
|
|
1578
|
+
computation: (curr, prev) => curr.held && prev !== undefined ? prev.value : curr.req });
|
|
1579
|
+
// Dedup via the request-equality (the linkedSignal re-runs on every source tick; this computed
|
|
1580
|
+
// is what actually gates httpResource — so an equal/held request never triggers a refetch).
|
|
1581
|
+
const stableRequest = computed(() => heldRequest(), { ...(ngDevMode ? { debugName: "stableRequest" } : /* istanbul ignore next */ {}), equal: (a, b) => {
|
|
1582
|
+
if (a === b)
|
|
1583
|
+
return true;
|
|
1584
|
+
if (a === undefined || b === undefined)
|
|
1585
|
+
return false;
|
|
1518
1586
|
if (eq)
|
|
1519
1587
|
return eq(a, b);
|
|
1520
1588
|
return a === b;
|
|
@@ -1579,7 +1647,8 @@ function queryResource(request, options) {
|
|
|
1579
1647
|
key: entry.key,
|
|
1580
1648
|
};
|
|
1581
1649
|
} });
|
|
1582
|
-
|
|
1650
|
+
// A disabled (offline / circuit-open / no-request) or PAUSED resource must not poll.
|
|
1651
|
+
resource = refresh(resource, destroyRef, options?.refresh, () => disabledReason() !== null);
|
|
1583
1652
|
resource = retryOnError(resource, options?.retry, options?.onError);
|
|
1584
1653
|
resource = persistResourceValues(resource, options?.keepPrevious, options?.equal);
|
|
1585
1654
|
const set = (value) => {
|
|
@@ -1609,7 +1678,7 @@ function queryResource(request, options) {
|
|
|
1609
1678
|
const client = options?.injector
|
|
1610
1679
|
? options.injector.get(HttpClient)
|
|
1611
1680
|
: inject(HttpClient);
|
|
1612
|
-
|
|
1681
|
+
const ref = {
|
|
1613
1682
|
...resource,
|
|
1614
1683
|
value,
|
|
1615
1684
|
set,
|
|
@@ -1677,6 +1746,9 @@ function queryResource(request, options) {
|
|
|
1677
1746
|
}
|
|
1678
1747
|
},
|
|
1679
1748
|
};
|
|
1749
|
+
// Auto-register into the nearest transition scope if the (merged) options ask for it.
|
|
1750
|
+
applyResourceRegistration(ref, options.register, options?.injector);
|
|
1751
|
+
return ref;
|
|
1680
1752
|
}
|
|
1681
1753
|
|
|
1682
1754
|
function manualQueryResource(request, options) {
|
|
@@ -1716,6 +1788,19 @@ function manualQueryResource(request, options) {
|
|
|
1716
1788
|
}
|
|
1717
1789
|
|
|
1718
1790
|
const NULL_VALUE = Symbol('@mmstack/resource:null');
|
|
1791
|
+
const MUTATION_RESOURCE_OPTIONS = new InjectionToken('@mmstack/resource:mutation-resource-options', { factory: () => ({}) });
|
|
1792
|
+
/**
|
|
1793
|
+
* Layer 2 (mutation): default options for every `mutationResource`, inheriting + overriding the
|
|
1794
|
+
* common defaults from `provideResourceOptions`. Per-call options override these in turn.
|
|
1795
|
+
*/
|
|
1796
|
+
function provideMutationResourceOptions(valueOrFn) {
|
|
1797
|
+
return provideTypedResourceOptions(MUTATION_RESOURCE_OPTIONS, valueOrFn);
|
|
1798
|
+
}
|
|
1799
|
+
function injectMutationResourceOptions(injector) {
|
|
1800
|
+
return injector
|
|
1801
|
+
? injector.get(MUTATION_RESOURCE_OPTIONS)
|
|
1802
|
+
: inject(MUTATION_RESOURCE_OPTIONS);
|
|
1803
|
+
}
|
|
1719
1804
|
/**
|
|
1720
1805
|
* Creates a resource for performing mutations (e.g., POST, PUT, PATCH, DELETE requests).
|
|
1721
1806
|
* Unlike `queryResource`, `mutationResource` is designed for one-off operations that change data.
|
|
@@ -1765,15 +1850,31 @@ const NULL_VALUE = Symbol('@mmstack/resource:null');
|
|
|
1765
1850
|
* );
|
|
1766
1851
|
* ```
|
|
1767
1852
|
*/
|
|
1768
|
-
function mutationResource(request,
|
|
1769
|
-
|
|
1770
|
-
const
|
|
1853
|
+
function mutationResource(request, options0 = {}) {
|
|
1854
|
+
// Two-layer option injection: per-call > provideMutationResourceOptions > provideResourceOptions.
|
|
1855
|
+
const options = {
|
|
1856
|
+
...injectResourceOptions(options0.injector),
|
|
1857
|
+
...injectMutationResourceOptions(options0.injector),
|
|
1858
|
+
...options0,
|
|
1859
|
+
};
|
|
1860
|
+
// `register` is pulled out (and forced off on the inner query below) so the mutation ref is
|
|
1861
|
+
// the only thing registered into the transition scope, not its internal query resource.
|
|
1862
|
+
const { onMutate, onError, onSuccess, onSettled, equal, register, equalRequest, ...rest } = options;
|
|
1863
|
+
const requestEqual = equalRequest ?? createEqualRequest(equal);
|
|
1864
|
+
// A mutation is an imperative command, so `triggerOnSameRequest` means "fire on EVERY mutate(),
|
|
1865
|
+
// even with an identical body". By default we dedup an identical value/request while one is in
|
|
1866
|
+
// flight (double-click protection); when this is set, both the `next` and `req` dedup are bypassed
|
|
1867
|
+
// so a repeat click isn't silently swallowed mid-flight. (Otherwise it'd be dropped until `next`
|
|
1868
|
+
// resets to NULL on settle — the "every other click" symptom.)
|
|
1869
|
+
const triggerOnSame = options.triggerOnSameRequest ?? false;
|
|
1771
1870
|
const eq = equal ?? Object.is;
|
|
1772
1871
|
const next = signal(NULL_VALUE, { ...(ngDevMode ? { debugName: "next" } : /* istanbul ignore next */ {}), equal: (a, b) => {
|
|
1773
1872
|
if (a === NULL_VALUE && b === NULL_VALUE)
|
|
1774
1873
|
return true;
|
|
1775
1874
|
if (a === NULL_VALUE || b === NULL_VALUE)
|
|
1776
1875
|
return false;
|
|
1876
|
+
if (triggerOnSame)
|
|
1877
|
+
return false;
|
|
1777
1878
|
return eq(a, b);
|
|
1778
1879
|
} });
|
|
1779
1880
|
const queue = signal([], ...(ngDevMode ? [{ debugName: "queue" }] : /* istanbul ignore next */ []));
|
|
@@ -1800,7 +1901,15 @@ function mutationResource(request, options = {}) {
|
|
|
1800
1901
|
if (nr === NULL_VALUE)
|
|
1801
1902
|
return;
|
|
1802
1903
|
return request(nr) ?? undefined;
|
|
1803
|
-
}, { ...(ngDevMode ? { debugName: "req" } : /* istanbul ignore next */ {}), equal:
|
|
1904
|
+
}, { ...(ngDevMode ? { debugName: "req" } : /* istanbul ignore next */ {}), equal: (a, b) => {
|
|
1905
|
+
if (a === undefined && b === undefined)
|
|
1906
|
+
return true;
|
|
1907
|
+
if (a === undefined || b === undefined)
|
|
1908
|
+
return false;
|
|
1909
|
+
if (triggerOnSame)
|
|
1910
|
+
return false;
|
|
1911
|
+
return requestEqual(a, b);
|
|
1912
|
+
} });
|
|
1804
1913
|
const lastValue = linkedSignal({ ...(ngDevMode ? { debugName: "lastValue" } : /* istanbul ignore next */ {}), source: next,
|
|
1805
1914
|
computation: (next, prev) => {
|
|
1806
1915
|
if (next === NULL_VALUE && !!prev)
|
|
@@ -1812,13 +1921,21 @@ function mutationResource(request, options = {}) {
|
|
|
1812
1921
|
if (nr === NULL_VALUE)
|
|
1813
1922
|
return;
|
|
1814
1923
|
return request(nr) ?? undefined;
|
|
1815
|
-
}, { ...(ngDevMode ? { debugName: "lastValueRequest" } : /* istanbul ignore next */ {}), equal:
|
|
1924
|
+
}, { ...(ngDevMode ? { debugName: "lastValueRequest" } : /* istanbul ignore next */ {}), equal: (a, b) => {
|
|
1925
|
+
if (a === b)
|
|
1926
|
+
return true;
|
|
1927
|
+
if (a === undefined || b === undefined)
|
|
1928
|
+
return false;
|
|
1929
|
+
return requestEqual(a, b);
|
|
1930
|
+
} });
|
|
1816
1931
|
const cb = createCircuitBreaker(options?.circuitBreaker === true
|
|
1817
1932
|
? undefined
|
|
1818
1933
|
: (options?.circuitBreaker ?? false), options?.injector);
|
|
1819
1934
|
const resource = queryResource(req, {
|
|
1820
1935
|
...rest,
|
|
1936
|
+
register: false, // the mutation ref handles registration; never register the inner query
|
|
1821
1937
|
circuitBreaker: cb,
|
|
1938
|
+
equalRequest: requestEqual,
|
|
1822
1939
|
defaultValue: NULL_VALUE, // doesnt matter since .value is not accessible
|
|
1823
1940
|
});
|
|
1824
1941
|
const destroyRef = options.injector
|
|
@@ -1852,7 +1969,7 @@ function mutationResource(request, options = {}) {
|
|
|
1852
1969
|
next.set(NULL_VALUE);
|
|
1853
1970
|
});
|
|
1854
1971
|
const shouldQueue = options.queue ?? false;
|
|
1855
|
-
|
|
1972
|
+
const ref = {
|
|
1856
1973
|
...resource,
|
|
1857
1974
|
destroy: () => {
|
|
1858
1975
|
statusSub.unsubscribe();
|
|
@@ -1883,11 +2000,13 @@ function mutationResource(request, options = {}) {
|
|
|
1883
2000
|
// redeclare disabled with last value so that it is not affected by the resource's internal disablement logic
|
|
1884
2001
|
disabled: computed(() => cb.isOpen() || lastValueRequest() === undefined),
|
|
1885
2002
|
};
|
|
2003
|
+
applyResourceRegistration(ref, register, options0.injector);
|
|
2004
|
+
return ref;
|
|
1886
2005
|
}
|
|
1887
2006
|
|
|
1888
2007
|
/**
|
|
1889
2008
|
* Generated bundle index. Do not edit.
|
|
1890
2009
|
*/
|
|
1891
2010
|
|
|
1892
|
-
export { Cache, createCacheInterceptor, createCircuitBreaker, createDedupeRequestsInterceptor, injectQueryCache, manualQueryResource, mutationResource, noDedupe, provideCircuitBreakerDefaultOptions, provideQueryCache, queryResource };
|
|
2011
|
+
export { Cache, PAUSED, applyResourceRegistration, createCacheInterceptor, createCircuitBreaker, createDedupeRequestsInterceptor, injectQueryCache, injectResourceOptions, manualQueryResource, mutationResource, noDedupe, provideCircuitBreakerDefaultOptions, provideMutationResourceOptions, provideQueryCache, provideQueryResourceOptions, provideResourceOptions, provideTypedResourceOptions, queryResource };
|
|
1893
2012
|
//# sourceMappingURL=mmstack-resource.mjs.map
|