@mmstack/resource 20.4.1 → 21.0.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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2025-present Miha J. Mulec
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2025-present Miha J. Mulec
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,120 +1,120 @@
1
- # @mmstack/resource
2
-
3
- [![npm version](https://badge.fury.io/js/%40mmstack%2Fresource.svg)](https://www.npmjs.com/package/@mmstack/resource)
4
- [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/mihajm/mmstack/blob/master/packages/resource/LICENSE)
5
-
6
- `@mmstack/resource` is an Angular library that provides powerful, signal-based primitives for managing asynchronous data fetching and mutations. It builds upon Angular's `httpResource` and offers features like caching, retries, refresh intervals, circuit breakers, and request deduplication, all while maintaining a fine-grained reactive graph. It's inspired by libraries like TanStack Query, but aims for a more Angular-idiomatic and signal-centric approach.
7
-
8
- ## Features
9
-
10
- - **Signal-Based:** Fully integrates with Angular's signal system for efficient change detection and reactivity.
11
- - **Caching:** Built-in caching with configurable TTL (Time To Live) and stale-while-revalidate behavior. Supports custom cache key generation and respects HTTP caching headers.
12
- - **Retries:** Automatic retries on failure with configurable backoff strategies.
13
- - **Refresh Intervals:** Automatically refetch data at specified intervals.
14
- - **Circuit Breaker:** Protects your application from cascading failures by temporarily disabling requests to failing endpoints.
15
- - **Request Deduplication:** Avoids making multiple identical requests concurrently.
16
- - **Mutations:** Provides a dedicated `mutationResource` for handling data modifications, with callbacks for `onMutate`, `onError`, `onSuccess`, and `onSettled`.
17
- - **Prefetching:** Allows you to prefetch data into the cache, improving perceived performance.
18
- - **Extensible:** Designed to be modular and extensible. You can easily add your own custom features or integrate with other libraries.
19
- - **TypeScript Support:** A strong focus on typesafety
20
-
21
- ## Quick Start
22
-
23
- 1. Install mmstack-resource
24
-
25
- ```bash
26
- npm install @mmstack/resource
27
- ```
28
-
29
- 2. Initialize the QueryCache & interceptors (optional)
30
-
31
- ```typescript
32
- import { provideHttpClient, withInterceptors } from '@angular/common/http';
33
- import { ApplicationConfig } from '@angular/core';
34
- import { createCacheInterceptor, createDedupeRequestsInterceptor, provideQueryCache } from '@mmstack/resource';
35
-
36
- export const appConfig: ApplicationConfig = {
37
- providers: [
38
- // ..other providers
39
- provideQueryCache(),
40
-
41
- // --- Example of a more advanced setup ---
42
- // provideQueryCache({
43
- // persist: true, // Enable IndexedDB persistence
44
- // version: 1, // Version for the cache schema
45
- // syncTabs: true // enable BroadcastChannel
46
- // }),
47
-
48
- provideHttpClient(withInterceptors([createCacheInterceptor(), createDedupeRequestsInterceptor()])),
49
- ],
50
- };
51
- ```
52
-
53
- 3. Use it :)
54
-
55
- ```typescript
56
- import { Injectable, isDevMode, untracked } from '@angular/core';
57
- import { createCircuitBreaker, mutationResource, queryResource } from '@mmstack/resource';
58
-
59
- type Post = {
60
- userId: number;
61
- id: number;
62
- title: string;
63
- body: string;
64
- };
65
-
66
- @Injectable({
67
- providedIn: 'root',
68
- })
69
- export class PostsService {
70
- private readonly endpoint = 'https://jsonplaceholder.typicode.com/posts';
71
- private readonly cb = createCircuitBreaker();
72
- readonly posts = queryResource<Post[]>(
73
- () => ({
74
- url: this.endpoint,
75
- }),
76
- {
77
- keepPrevious: true, // keep data between requests
78
- refresh: 5 * 60 * 1000, // refresh every 5 minutes
79
- circuitBreaker: this.cb, // use shared circuit breaker use true if not sharing
80
- retry: 3, // retry 3 times on error using default backoff
81
- onError: (err) => {
82
- if (!isDevMode()) return;
83
- console.error(err);
84
- }, // log errors in dev mode
85
- defaultValue: [],
86
- },
87
- );
88
-
89
- private readonly createPostResource = mutationResource(
90
- (post: Post) => ({
91
- url: this.endpoint,
92
- method: 'POST',
93
- body: post,
94
- }),
95
- {
96
- circuitBreaker: this.cb, // use shared circuit breaker use true if not sharing
97
- onMutate: (post: Post) => {
98
- const prev = untracked(this.posts.value);
99
- this.posts.set([...prev, post]); // optimistically update
100
- return prev;
101
- },
102
- onError: (err, prev) => {
103
- if (isDevMode()) console.error(err);
104
- this.posts.set(prev); // rollback on error
105
- },
106
- onSuccess: (next) => {
107
- this.posts.update((posts) => posts.map((p) => (p.id === next.id ? next : p))); // replace with value from server
108
- },
109
- },
110
- );
111
-
112
- createPost(post: Post) {
113
- this.createPostResource.mutate(post); // send the request
114
- }
115
- }
116
- ```
117
-
118
- ## In-depth
119
-
120
- For an in-depth explanation of the primitives & how they work check out this article: [Fun-grained Reactivity in Angular: Part 3 - Resources](https://dev.to/mihamulec/fun-grained-reactivity-in-angular-part-3-client-side-http-57g4)
1
+ # @mmstack/resource
2
+
3
+ [![npm version](https://badge.fury.io/js/%40mmstack%2Fresource.svg)](https://www.npmjs.com/package/@mmstack/resource)
4
+ [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/mihajm/mmstack/blob/master/packages/resource/LICENSE)
5
+
6
+ `@mmstack/resource` is an Angular library that provides powerful, signal-based primitives for managing asynchronous data fetching and mutations. It builds upon Angular's `httpResource` and offers features like caching, retries, refresh intervals, circuit breakers, and request deduplication, all while maintaining a fine-grained reactive graph. It's inspired by libraries like TanStack Query, but aims for a more Angular-idiomatic and signal-centric approach.
7
+
8
+ ## Features
9
+
10
+ - **Signal-Based:** Fully integrates with Angular's signal system for efficient change detection and reactivity.
11
+ - **Caching:** Built-in caching with configurable TTL (Time To Live) and stale-while-revalidate behavior. Supports custom cache key generation and respects HTTP caching headers.
12
+ - **Retries:** Automatic retries on failure with configurable backoff strategies.
13
+ - **Refresh Intervals:** Automatically refetch data at specified intervals.
14
+ - **Circuit Breaker:** Protects your application from cascading failures by temporarily disabling requests to failing endpoints.
15
+ - **Request Deduplication:** Avoids making multiple identical requests concurrently.
16
+ - **Mutations:** Provides a dedicated `mutationResource` for handling data modifications, with callbacks for `onMutate`, `onError`, `onSuccess`, and `onSettled`.
17
+ - **Prefetching:** Allows you to prefetch data into the cache, improving perceived performance.
18
+ - **Extensible:** Designed to be modular and extensible. You can easily add your own custom features or integrate with other libraries.
19
+ - **TypeScript Support:** A strong focus on typesafety
20
+
21
+ ## Quick Start
22
+
23
+ 1. Install mmstack-resource
24
+
25
+ ```bash
26
+ npm install @mmstack/resource
27
+ ```
28
+
29
+ 2. Initialize the QueryCache & interceptors (optional)
30
+
31
+ ```typescript
32
+ import { provideHttpClient, withInterceptors } from '@angular/common/http';
33
+ import { ApplicationConfig } from '@angular/core';
34
+ import { createCacheInterceptor, createDedupeRequestsInterceptor, provideQueryCache } from '@mmstack/resource';
35
+
36
+ export const appConfig: ApplicationConfig = {
37
+ providers: [
38
+ // ..other providers
39
+ provideQueryCache(),
40
+
41
+ // --- Example of a more advanced setup ---
42
+ // provideQueryCache({
43
+ // persist: true, // Enable IndexedDB persistence
44
+ // version: 1, // Version for the cache schema
45
+ // syncTabs: true // enable BroadcastChannel
46
+ // }),
47
+
48
+ provideHttpClient(withInterceptors([createCacheInterceptor(), createDedupeRequestsInterceptor()])),
49
+ ],
50
+ };
51
+ ```
52
+
53
+ 3. Use it :)
54
+
55
+ ```typescript
56
+ import { Injectable, isDevMode, untracked } from '@angular/core';
57
+ import { createCircuitBreaker, mutationResource, queryResource } from '@mmstack/resource';
58
+
59
+ type Post = {
60
+ userId: number;
61
+ id: number;
62
+ title: string;
63
+ body: string;
64
+ };
65
+
66
+ @Injectable({
67
+ providedIn: 'root',
68
+ })
69
+ export class PostsService {
70
+ private readonly endpoint = 'https://jsonplaceholder.typicode.com/posts';
71
+ private readonly cb = createCircuitBreaker();
72
+ readonly posts = queryResource<Post[]>(
73
+ () => ({
74
+ url: this.endpoint,
75
+ }),
76
+ {
77
+ keepPrevious: true, // keep data between requests
78
+ refresh: 5 * 60 * 1000, // refresh every 5 minutes
79
+ circuitBreaker: this.cb, // use shared circuit breaker use true if not sharing
80
+ retry: 3, // retry 3 times on error using default backoff
81
+ onError: (err) => {
82
+ if (!isDevMode()) return;
83
+ console.error(err);
84
+ }, // log errors in dev mode
85
+ defaultValue: [],
86
+ },
87
+ );
88
+
89
+ private readonly createPostResource = mutationResource(
90
+ (post: Post) => ({
91
+ url: this.endpoint,
92
+ method: 'POST',
93
+ body: post,
94
+ }),
95
+ {
96
+ circuitBreaker: this.cb, // use shared circuit breaker use true if not sharing
97
+ onMutate: (post: Post) => {
98
+ const prev = untracked(this.posts.value);
99
+ this.posts.set([...prev, post]); // optimistically update
100
+ return prev;
101
+ },
102
+ onError: (err, prev) => {
103
+ if (isDevMode()) console.error(err);
104
+ this.posts.set(prev); // rollback on error
105
+ },
106
+ onSuccess: (next) => {
107
+ this.posts.update((posts) => posts.map((p) => (p.id === next.id ? next : p))); // replace with value from server
108
+ },
109
+ },
110
+ );
111
+
112
+ createPost(post: Post) {
113
+ this.createPostResource.mutate(post); // send the request
114
+ }
115
+ }
116
+ ```
117
+
118
+ ## In-depth
119
+
120
+ For an in-depth explanation of the primitives & how they work check out this article: [Fun-grained Reactivity in Angular: Part 3 - Resources](https://dev.to/mihamulec/fun-grained-reactivity-in-angular-part-3-client-side-http-57g4)
@@ -1178,15 +1178,13 @@ function hasSlowConnection() {
1178
1178
 
1179
1179
  function persist(src, equal) {
1180
1180
  // linkedSignal allows us to access previous source value
1181
- const persisted = linkedSignal({
1182
- source: () => src(),
1181
+ const persisted = linkedSignal({ ...(ngDevMode ? { debugName: "persisted" } : {}), source: () => src(),
1183
1182
  computation: (next, prev) => {
1184
1183
  if (next === undefined && prev !== undefined)
1185
1184
  return prev.value;
1186
1185
  return next;
1187
1186
  },
1188
- equal,
1189
- });
1187
+ equal });
1190
1188
  // if original value was WritableSignal then override linkedSignal methods to original...angular uses linkedSignal under the hood in ResourceImpl, this applies to that.
1191
1189
  if ('set' in src) {
1192
1190
  persisted.set = src.set;
@@ -1271,10 +1269,10 @@ function retryOnError(res, opt) {
1271
1269
 
1272
1270
  class ResourceSensors {
1273
1271
  networkStatus = sensor('networkStatus');
1274
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.1", ngImport: i0, type: ResourceSensors, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1275
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.1", ngImport: i0, type: ResourceSensors, providedIn: 'root' });
1272
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.0.8", ngImport: i0, type: ResourceSensors, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1273
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.0.8", ngImport: i0, type: ResourceSensors, providedIn: 'root' });
1276
1274
  }
1277
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.1", ngImport: i0, type: ResourceSensors, decorators: [{
1275
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.0.8", ngImport: i0, type: ResourceSensors, decorators: [{
1278
1276
  type: Injectable,
1279
1277
  args: [{
1280
1278
  providedIn: 'root',
@@ -1341,17 +1339,11 @@ function queryResource(request, options) {
1341
1339
  if (!networkAvailable() || cb.isOpen())
1342
1340
  return undefined;
1343
1341
  return request() ?? undefined;
1344
- }, ...(ngDevMode ? [{ debugName: "stableRequest", equal: (a, b) => {
1345
- if (eq)
1346
- return eq(a, b);
1347
- return a === b;
1348
- } }] : [{
1349
- equal: (a, b) => {
1350
- if (eq)
1351
- return eq(a, b);
1352
- return a === b;
1353
- },
1354
- }]));
1342
+ }, { ...(ngDevMode ? { debugName: "stableRequest" } : {}), equal: (a, b) => {
1343
+ if (eq)
1344
+ return eq(a, b);
1345
+ return a === b;
1346
+ } });
1355
1347
  const hashFn = typeof options?.cache === 'object'
1356
1348
  ? (options.cache.hash ?? urlWithParams)
1357
1349
  : urlWithParams;
@@ -1393,8 +1385,7 @@ function queryResource(request, options) {
1393
1385
  resource = catchValueError(resource, options?.defaultValue);
1394
1386
  // get full HttpResonse from Cache
1395
1387
  const cachedEvent = cache.getEntryOrKey(cacheKey);
1396
- const cacheEntry = linkedSignal({
1397
- source: () => cachedEvent(),
1388
+ const cacheEntry = linkedSignal({ ...(ngDevMode ? { debugName: "cacheEntry" } : {}), source: () => cachedEvent(),
1398
1389
  computation: (entry, prev) => {
1399
1390
  if (!entry)
1400
1391
  return null;
@@ -1412,8 +1403,7 @@ function queryResource(request, options) {
1412
1403
  value: entry.value.body,
1413
1404
  key: entry.key,
1414
1405
  };
1415
- },
1416
- });
1406
+ } });
1417
1407
  resource = refresh(resource, destroyRef, options?.refresh);
1418
1408
  resource = retryOnError(resource, options?.retry);
1419
1409
  resource = persistResourceValues(resource, options?.keepPrevious, options?.equal);
@@ -1498,6 +1488,7 @@ function queryResource(request, options) {
1498
1488
  try {
1499
1489
  await firstValueFrom(client.request(prefetchRequest.method ?? 'GET', prefetchRequest.url, {
1500
1490
  ...prefetchRequest,
1491
+ referrerPolicy: prefetchRequest.referrerPolicy,
1501
1492
  credentials: prefetchRequest.credentials,
1502
1493
  priority: prefetchRequest.priority,
1503
1494
  cache: prefetchRequest.cache,
@@ -1551,21 +1542,13 @@ function mutationResource(request, options = {}) {
1551
1542
  const { onMutate, onError, onSuccess, onSettled, equal, ...rest } = options;
1552
1543
  const requestEqual = createEqualRequest(equal);
1553
1544
  const eq = equal ?? Object.is;
1554
- const next = signal(null, ...(ngDevMode ? [{ debugName: "next", equal: (a, b) => {
1555
- if (!a && !b)
1556
- return true;
1557
- if (!a || !b)
1558
- return false;
1559
- return eq(a, b);
1560
- } }] : [{
1561
- equal: (a, b) => {
1562
- if (!a && !b)
1563
- return true;
1564
- if (!a || !b)
1565
- return false;
1566
- return eq(a, b);
1567
- },
1568
- }]));
1545
+ const next = signal(null, { ...(ngDevMode ? { debugName: "next" } : {}), equal: (a, b) => {
1546
+ if (!a && !b)
1547
+ return true;
1548
+ if (!a || !b)
1549
+ return false;
1550
+ return eq(a, b);
1551
+ } });
1569
1552
  const queue = signal([], ...(ngDevMode ? [{ debugName: "queue" }] : []));
1570
1553
  let ctx = undefined;
1571
1554
  const queueRef = effect(() => {
@@ -1582,25 +1565,19 @@ function mutationResource(request, options = {}) {
1582
1565
  if (!nr)
1583
1566
  return;
1584
1567
  return request(nr) ?? undefined;
1585
- }, ...(ngDevMode ? [{ debugName: "req", equal: requestEqual }] : [{
1586
- equal: requestEqual,
1587
- }]));
1588
- const lastValue = linkedSignal({
1589
- source: next,
1568
+ }, { ...(ngDevMode ? { debugName: "req" } : {}), equal: requestEqual });
1569
+ const lastValue = linkedSignal({ ...(ngDevMode ? { debugName: "lastValue" } : {}), source: next,
1590
1570
  computation: (next, prev) => {
1591
1571
  if (next === null && !!prev)
1592
1572
  return prev.value;
1593
1573
  return next;
1594
- },
1595
- });
1574
+ } });
1596
1575
  const lastValueRequest = computed(() => {
1597
1576
  const nr = lastValue();
1598
1577
  if (!nr)
1599
1578
  return;
1600
1579
  return request(nr) ?? undefined;
1601
- }, ...(ngDevMode ? [{ debugName: "lastValueRequest", equal: requestEqual }] : [{
1602
- equal: requestEqual,
1603
- }]));
1580
+ }, { ...(ngDevMode ? { debugName: "lastValueRequest" } : {}), equal: requestEqual });
1604
1581
  const cb = createCircuitBreaker(options?.circuitBreaker === true
1605
1582
  ? undefined
1606
1583
  : (options?.circuitBreaker ?? false), options?.injector);