@mmstack/resource 19.2.0 → 20.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/index.d.ts CHANGED
@@ -1 +1,520 @@
1
- export * from './lib/public_api';
1
+ import { HttpResponse, HttpInterceptorFn, HttpContext, HttpResourceOptions, HttpResourceRequest, HttpResourceRef } from '@angular/common/http';
2
+ import { Signal, Injector, Provider, ValueEqualityFn } from '@angular/core';
3
+
4
+ /**
5
+ * Options for configuring the Least Recently Used (LRU) cache cleanup strategy.
6
+ * @internal
7
+ */
8
+ type LRUCleanupType = {
9
+ type: 'lru';
10
+ /**
11
+ * How often to check for expired or excess entries, in milliseconds.
12
+ */
13
+ checkInterval: number;
14
+ /**
15
+ * The maximum number of entries to keep in the cache. When the cache exceeds this size,
16
+ * the least recently used entries will be removed.
17
+ */
18
+ maxSize: number;
19
+ };
20
+ /**
21
+ * Options for configuring the "oldest first" cache cleanup strategy.
22
+ * @internal
23
+ */
24
+ type OldsetCleanupType = {
25
+ type: 'oldest';
26
+ /**
27
+ * How often to check for expired or excess entries, in milliseconds.
28
+ */
29
+ checkInterval: number;
30
+ /**
31
+ * The maximum number of entries to keep in the cache. When the cache exceeds this size,
32
+ * the oldest entries will be removed.
33
+ */
34
+ maxSize: number;
35
+ };
36
+ /**
37
+ * Represents an entry in the cache.
38
+ * @internal
39
+ */
40
+ type CacheEntry<T> = {
41
+ value: T;
42
+ created: number;
43
+ stale: number;
44
+ useCount: number;
45
+ expiresAt: number;
46
+ timeout: ReturnType<typeof setTimeout>;
47
+ };
48
+ /**
49
+ * Defines the types of cleanup strategies available for the cache.
50
+ * - `lru`: Least Recently Used. Removes the least recently accessed entries when the cache is full.
51
+ * - `oldest`: Removes the oldest entries when the cache is full.
52
+ */
53
+ type CleanupType = LRUCleanupType | OldsetCleanupType;
54
+ /**
55
+ * A generic cache implementation that stores data with time-to-live (TTL) and stale-while-revalidate capabilities.
56
+ *
57
+ * @typeParam T - The type of data to be stored in the cache.
58
+ */
59
+ declare class Cache<T> {
60
+ protected readonly ttl: number;
61
+ protected readonly staleTime: number;
62
+ private readonly internal;
63
+ private readonly cleanupOpt;
64
+ /**
65
+ * Creates a new `Cache` instance.
66
+ *
67
+ * @param ttl - The default Time To Live (TTL) for cache entries, in milliseconds. Defaults to one day.
68
+ * @param staleTime - The default duration, in milliseconds, during which a cache entry is considered
69
+ * stale but can still be used while revalidation occurs in the background. Defaults to 1 hour.
70
+ * @param cleanupOpt - Options for configuring the cache cleanup strategy. Defaults to LRU with a
71
+ * `maxSize` of 200 and a `checkInterval` of one hour.
72
+ */
73
+ constructor(ttl?: number, staleTime?: number, cleanupOpt?: Partial<CleanupType>);
74
+ /** @internal */
75
+ private getInternal;
76
+ /**
77
+ * Retrieves a cache entry without affecting its usage count (for LRU). This is primarily
78
+ * for internal use or debugging.
79
+ * @internal
80
+ * @param key - The key of the entry to retrieve.
81
+ * @returns The cache entry, or `null` if not found or expired.
82
+ */
83
+ getUntracked(key: string): (CacheEntry<T> & {
84
+ isStale: boolean;
85
+ }) | null;
86
+ /**
87
+ * Retrieves a cache entry as a signal.
88
+ *
89
+ * @param key - A function that returns the cache key. The key is a signal, allowing for dynamic keys. If the function returns null the value is also null.
90
+ * @returns A signal that holds the cache entry, or `null` if not found or expired. The signal
91
+ * updates whenever the cache entry changes (e.g., due to revalidation or expiration).
92
+ */
93
+ get(key: () => string | null): Signal<(CacheEntry<T> & {
94
+ isStale: boolean;
95
+ }) | null>;
96
+ /**
97
+ * Stores a value in the cache.
98
+ *
99
+ * @param key - The key under which to store the value.
100
+ * @param value - The value to store.
101
+ * @param staleTime - (Optional) The stale time for this entry, in milliseconds. Overrides the default `staleTime`.
102
+ * @param ttl - (Optional) The TTL for this entry, in milliseconds. Overrides the default `ttl`.
103
+ */
104
+ store(key: string, value: T, staleTime?: number, ttl?: number): void;
105
+ /**
106
+ * Invalidates (removes) a cache entry.
107
+ *
108
+ * @param key - The key of the entry to invalidate.
109
+ */
110
+ invalidate(key: string): void;
111
+ /** @internal */
112
+ private cleanup;
113
+ }
114
+ /**
115
+ * Options for configuring the cache.
116
+ */
117
+ type CacheOptions = {
118
+ /**
119
+ * The default Time To Live (TTL) for cache entries, in milliseconds.
120
+ */
121
+ ttl?: number;
122
+ /**
123
+ * The default duration, in milliseconds, during which a cache entry is considered
124
+ * stale but can still be used while revalidation occurs in the background.
125
+ */
126
+ staleTime?: number;
127
+ /**
128
+ * Options for configuring the cache cleanup strategy.
129
+ */
130
+ cleanup?: Partial<CleanupType>;
131
+ };
132
+ /**
133
+ * Provides the instance of the QueryCache for queryResource. This should probably be called
134
+ * in your application's root configuration, but can also be overriden with component/module providers.
135
+ *
136
+ * @param options - Optional configuration options for the cache.
137
+ * @returns An Angular `Provider` for the cache.
138
+ *
139
+ * @example
140
+ * // In your app.config.ts or AppModule providers:
141
+ *
142
+ * import { provideQueryCache } from './your-cache';
143
+ *
144
+ * export const appConfig: ApplicationConfig = {
145
+ * providers: [
146
+ * provideQueryCache({
147
+ * ttl: 60000, // Default TTL of 60 seconds
148
+ * staleTime: 30000, // Default staleTime of 30 seconds
149
+ * }),
150
+ * // ... other providers
151
+ * ]
152
+ * };
153
+ */
154
+ declare function provideQueryCache(opt?: CacheOptions): Provider;
155
+ /**
156
+ * Injects the `QueryCache` instance that is used within queryResource.
157
+ * Allows for direct modification of cached data, but is mostly meant for internal use.
158
+ *
159
+ * @param injector - (Optional) The injector to use. If not provided, the current
160
+ * injection context is used.
161
+ * @returns The `QueryCache` instance.
162
+ *
163
+ * @example
164
+ * // In your component or service:
165
+ *
166
+ * import { injectQueryCache } from './your-cache';
167
+ *
168
+ * constructor() {
169
+ * const cache = injectQueryCache();
170
+ *
171
+ * const myData = cache.get(() => 'my-data-key');
172
+ * if (myData() !== null) {
173
+ * // ... use cached data ...
174
+ * }
175
+ * }
176
+ */
177
+ declare function injectQueryCache(injector?: Injector): Cache<HttpResponse<unknown>>;
178
+
179
+ /**
180
+ * Creates an `HttpInterceptorFn` that implements caching for HTTP requests. This interceptor
181
+ * checks for a caching configuration in the request's `HttpContext` (internally set by the queryResource).
182
+ * If caching is enabled, it attempts to retrieve responses from the cache. If a cached response
183
+ * is found and is not stale, it's returned directly. If the cached response is stale, it's returned,
184
+ * and a background revalidation request is made. If no cached response is found, the request
185
+ * is made to the server, and the response is cached according to the configured TTL and staleness.
186
+ * The interceptor also respects `Cache-Control` headers from the server.
187
+ *
188
+ * @param allowedMethods - An array of HTTP methods for which caching should be enabled.
189
+ * Defaults to `['GET', 'HEAD', 'OPTIONS']`.
190
+ *
191
+ * @returns An `HttpInterceptorFn` that implements the caching logic.
192
+ *
193
+ * @example
194
+ * // In your app.config.ts or module providers:
195
+ *
196
+ * import { provideHttpClient, withInterceptors } from '@angular/common/http';
197
+ * import { createCacheInterceptor } from '@mmstack/resource';
198
+ *
199
+ * export const appConfig: ApplicationConfig = {
200
+ * providers: [
201
+ * provideHttpClient(withInterceptors([createCacheInterceptor()])),
202
+ * // ... other providers
203
+ * ],
204
+ * };
205
+ */
206
+ declare function createCacheInterceptor(allowedMethods?: string[]): HttpInterceptorFn;
207
+
208
+ /**
209
+ * Represents the possible states of a circuit breaker.
210
+ * - `CLOSED`: The circuit breaker is closed, and operations are allowed to proceed.
211
+ * - `OPEN`: The circuit breaker is open, and operations are blocked.
212
+ * - `HALF_OPEN`: The circuit breaker is in a half-open state, allowing a limited number of operations to test if the underlying issue is resolved.
213
+ */
214
+ type CircuitBreakerState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
215
+ /**
216
+ * Represents a circuit breaker, which monitors operations and prevents failures from cascading.
217
+ */
218
+ type CircuitBreaker = {
219
+ /**
220
+ * A signal indicating whether the circuit breaker is currently closed (allowing operations).
221
+ */
222
+ isClosed: Signal<boolean>;
223
+ /**
224
+ * A signal representing the current state of the circuit breaker.
225
+ */
226
+ status: Signal<CircuitBreakerState>;
227
+ /**
228
+ * Signals a failure to the circuit breaker. This may cause the circuit breaker to open.
229
+ */
230
+ fail: () => void;
231
+ /**
232
+ * Signals a success to the circuit breaker. This may cause the circuit breaker to close.
233
+ */
234
+ success: () => void;
235
+ /**
236
+ * Attempts to transition the circuit breaker to the half-open state. This is typically used
237
+ * to test if the underlying issue has been resolved after the circuit breaker has been open.
238
+ */
239
+ halfOpen: () => void;
240
+ /**
241
+ * Destroys the circuit breaker & initiates related cleanup
242
+ */
243
+ destroy: () => void;
244
+ };
245
+ /**
246
+ * Options for creating a circuit breaker.
247
+ * - `false`: Disables circuit breaker functionality (always open).
248
+ * - true: Creates a new circuit breaker with default options.
249
+ * - `CircuitBreaker`: Provides an existing `CircuitBreaker` instance to use.
250
+ * - `{ treshold?: number; timeout?: number; }`: Creates a new circuit breaker with the specified options.
251
+ */
252
+ type CircuitBreakerOptions = false | CircuitBreaker | {
253
+ treshold?: number;
254
+ timeout?: number;
255
+ };
256
+ /**
257
+ * Creates a circuit breaker instance.
258
+ *
259
+ * @param options - Configuration options for the circuit breaker. Can be:
260
+ * - `undefined`: Creates a "no-op" circuit breaker that is always open (never trips).
261
+ * - `true`: Creates a circuit breaker with default settings (threshold: 5, timeout: 30000ms).
262
+ * - `CircuitBreaker`: Reuses an existing `CircuitBreaker` instance.
263
+ * - `{ threshold?: number; timeout?: number; }`: Creates a circuit breaker with the specified threshold and timeout.
264
+ *
265
+ * @returns A `CircuitBreaker` instance.
266
+ *
267
+ * @example
268
+ * // Create a circuit breaker with default settings:
269
+ * const breaker = createCircuitBreaker();
270
+ *
271
+ * // Create a circuit breaker with custom settings:
272
+ * const customBreaker = createCircuitBreaker({ threshold: 10, timeout: 60000 });
273
+ *
274
+ * // Share a single circuit breaker instance across multiple resources:
275
+ * const sharedBreaker = createCircuitBreaker();
276
+ * const resource1 = queryResource(..., { circuitBreaker: sharedBreaker });
277
+ * const resource2 = mutationResource(..., { circuitBreaker: sharedBreaker });
278
+ */
279
+ declare function createCircuitBreaker(opt?: CircuitBreakerOptions): CircuitBreaker;
280
+
281
+ /**
282
+ * Disables request deduplication for a specific HTTP request.
283
+ *
284
+ * @param ctx - The `HttpContext` to modify. If not provided, a new `HttpContext` is created.
285
+ * @returns The modified `HttpContext` with the `NO_DEDUPE` token set to `true`.
286
+ *
287
+ * @example
288
+ * // Disable deduplication for a specific POST request:
289
+ * const context = noDedupe();
290
+ * this.http.post('/api/data', payload, { context }).subscribe(...);
291
+ *
292
+ * // Disable deduplication, modifying an existing context:
293
+ * let context = new HttpContext();
294
+ * context = noDedupe(context);
295
+ * this.http.post('/api/data', payload, { context }).subscribe(...);
296
+ */
297
+ declare function noDedupe(ctx?: HttpContext): HttpContext;
298
+ /**
299
+ * Creates an `HttpInterceptorFn` that deduplicates identical HTTP requests.
300
+ * If multiple identical requests (same URL and parameters) are made concurrently,
301
+ * only the first request will be sent to the server. Subsequent requests will
302
+ * receive the response from the first request.
303
+ *
304
+ * @param allowed - An array of HTTP methods for which deduplication should be enabled.
305
+ * Defaults to `['GET', 'DELETE', 'HEAD', 'OPTIONS']`.
306
+ *
307
+ * @returns An `HttpInterceptorFn` that implements the request deduplication logic.
308
+ *
309
+ * @example
310
+ * // In your app.config.ts or module providers:
311
+ * import { provideHttpClient, withInterceptors } from '@angular/common/http';
312
+ * import { createDedupeRequestsInterceptor } from './your-dedupe-interceptor';
313
+ *
314
+ * export const appConfig: ApplicationConfig = {
315
+ * providers: [
316
+ * provideHttpClient(withInterceptors([createDedupeRequestsInterceptor()])),
317
+ * // ... other providers
318
+ * ],
319
+ * };
320
+ *
321
+ * // You can also specify which methods should be deduped
322
+ * export const appConfig: ApplicationConfig = {
323
+ * providers: [
324
+ * provideHttpClient(withInterceptors([createDedupeRequestsInterceptor(['GET'])])), // only dedupe GET calls
325
+ * // ... other providers
326
+ * ],
327
+ * };
328
+ */
329
+ declare function createDedupeRequestsInterceptor(allowed?: string[]): HttpInterceptorFn;
330
+
331
+ type RetryOptions = number | {
332
+ max?: number;
333
+ backoff?: number;
334
+ };
335
+
336
+ /**
337
+ * Options for configuring caching behavior of a `queryResource`.
338
+ * - `true`: Enables caching with default settings.
339
+ * - `{ ttl?: number; staleTime?: number; hash?: (req: HttpResourceRequest) => string; }`: Configures caching with custom settings.
340
+ */
341
+ type ResourceCacheOptions = true | {
342
+ /**
343
+ * The Time To Live (TTL) for the cached data, in milliseconds. After this time, the cached data is
344
+ * considered expired and will be refetched.
345
+ */
346
+ ttl?: number;
347
+ /**
348
+ * The duration, in milliseconds, during which stale data can be served while a revalidation request
349
+ * is made in the background.
350
+ */
351
+ staleTime?: number;
352
+ /**
353
+ * A custom function to generate the cache key. Defaults to using the request URL with parameters.
354
+ * Provide a custom hash function if you need more control over how cache keys are generated,
355
+ * for instance, to ignore certain query parameters or to use request body for the cache key.
356
+ */
357
+ hash?: (req: HttpResourceRequest) => string;
358
+ };
359
+ /**
360
+ * Options for configuring a `queryResource`.
361
+ */
362
+ type QueryResourceOptions<TResult, TRaw = TResult> = HttpResourceOptions<TResult, TRaw> & {
363
+ /**
364
+ * Whether to keep the previous value of the resource while a refresh is in progress.
365
+ * Defaults to `false`. Also keeps status & headers while refreshing.
366
+ */
367
+ keepPrevious?: boolean;
368
+ /**
369
+ * The refresh interval, in milliseconds. If provided, the resource will automatically
370
+ * refresh its data at the specified interval.
371
+ */
372
+ refresh?: number;
373
+ /**
374
+ * Options for retrying failed requests.
375
+ */
376
+ retry?: RetryOptions;
377
+ /**
378
+ * An optional error handler callback. This function will be called whenever the
379
+ * underlying HTTP request fails. Useful for displaying toasts or other error messages.
380
+ */
381
+ onError?: (err: unknown) => void;
382
+ /**
383
+ * Options for configuring a circuit breaker for the resource.
384
+ */
385
+ circuitBreaker?: CircuitBreakerOptions | true;
386
+ /**
387
+ * Options for enabling and configuring caching for the resource.
388
+ */
389
+ cache?: ResourceCacheOptions;
390
+ /**
391
+ * Trigger a request every time the request function is triggered, even if the request parameters are the same.
392
+ * @default false
393
+ */
394
+ triggerOnSameRequest?: boolean;
395
+ };
396
+ /**
397
+ * Represents a resource created by `queryResource`. Extends `HttpResourceRef` with additional properties.
398
+ */
399
+ type QueryResourceRef<TResult> = HttpResourceRef<TResult> & {
400
+ /**
401
+ * A signal indicating whether the resource is currently disabled (due to circuit breaker or undefined request).
402
+ */
403
+ disabled: Signal<boolean>;
404
+ /**
405
+ * Prefetches data for the resource, populating the cache if caching is enabled. This can be
406
+ * used to proactively load data before it's needed. If a slow connection is detected, prefetching is skipped.
407
+ *
408
+ * @param req - Optional partial request parameters to use for the prefetch. This allows you
409
+ * to prefetch data with different parameters than the main resource request.
410
+ */
411
+ prefetch: (req?: Partial<HttpResourceRequest>) => Promise<void>;
412
+ };
413
+ declare function queryResource<TResult, TRaw = TResult>(request: () => HttpResourceRequest | undefined | void, options: QueryResourceOptions<TResult, TRaw> & {
414
+ defaultValue: NoInfer<TResult>;
415
+ }): QueryResourceRef<TResult>;
416
+ /**
417
+ * Creates an extended HTTP resource with features like caching, retries, refresh intervals,
418
+ * circuit breaker, and optimistic updates. Without additional options it is equivalent to simply calling `httpResource`.
419
+ *
420
+ * @param request A function that returns the `HttpResourceRequest` to be made. This function
421
+ * is called reactively, so the request can change over time. If the function
422
+ * returns `undefined`, the resource is considered "disabled" and no request will be made.
423
+ * @param options Configuration options for the resource. These options extend the basic
424
+ * `HttpResourceOptions` and add features like `keepPrevious`, `refresh`, `retry`,
425
+ * `onError`, `circuitBreaker`, and `cache`.
426
+ * @returns An `QueryResourceRef` instance, which extends the basic `HttpResourceRef` with additional features.
427
+ */
428
+ declare function queryResource<TResult, TRaw = TResult>(request: () => HttpResourceRequest | undefined | void, options?: QueryResourceOptions<TResult, TRaw>): QueryResourceRef<TResult | undefined>;
429
+
430
+ /**
431
+ * @internal
432
+ * Helper type for inferring the request body type based on the HTTP method.
433
+ */
434
+ type NextRequest<TMethod extends HttpResourceRequest['method'], TMutation> = TMethod extends 'DELETE' | 'delete' ? Omit<HttpResourceRequest, 'body' | 'method'> & {
435
+ method?: TMethod;
436
+ } : Omit<HttpResourceRequest, 'body' | 'method'> & {
437
+ body: TMutation;
438
+ method?: TMethod;
439
+ };
440
+ /**
441
+ * Options for configuring a `mutationResource`.
442
+ *
443
+ * @typeParam TResult - The type of the expected result from the mutation.
444
+ * @typeParam TRaw - The raw response type from the HTTP request (defaults to TResult).
445
+ * @typeParam TCTX - The type of the context value returned by `onMutate`.
446
+ */
447
+ type MutationResourceOptions<TResult, TRaw = TResult, TMutation = TResult, TCTX = void, TICTX = TCTX> = Omit<QueryResourceOptions<TResult, TRaw>, 'equal' | 'onError' | 'keepPrevious' | 'refresh' | 'cache'> & {
448
+ /**
449
+ * A callback function that is called before the mutation request is made.
450
+ * @param value The value being mutated (the `body` of the request).
451
+ * @returns An optional context value that will be passed to the `onError`, `onSuccess`, and `onSettled` callbacks. This is useful for storing
452
+ * information needed during the mutation lifecycle, such as previous values for optimistic updates or rollback.
453
+ */
454
+ onMutate?: (value: TMutation, initialCTX?: TICTX) => TCTX;
455
+ /**
456
+ * A callback function that is called if the mutation request fails.
457
+ * @param error The error that occurred.
458
+ * @param ctx The context value returned by the `onMutate` callback (or `undefined` if `onMutate` was not provided or returned `undefined`).
459
+ */
460
+ onError?: (error: unknown, ctx: NoInfer<TCTX>) => void;
461
+ /**
462
+ * A callback function that is called if the mutation request succeeds.
463
+ * @param value The result of the mutation (the parsed response body).
464
+ * @param ctx The context value returned by the `onMutate` callback (or `undefined` if `onMutate` was not provided or returned `undefined`).
465
+ */
466
+ onSuccess?: (value: NoInfer<TResult>, ctx: NoInfer<TCTX>) => void;
467
+ /**
468
+ * A callback function that is called when the mutation request settles (either succeeds or fails).
469
+ * @param ctx The context value returned by the `onMutate` callback (or `undefined` if `onMutate` was not provided or returned `undefined`).
470
+ */
471
+ onSettled?: (ctx: NoInfer<TCTX>) => void;
472
+ equal?: ValueEqualityFn<TMutation>;
473
+ };
474
+ /**
475
+ * Represents a mutation resource created by `mutationResource`. Extends `QueryResourceRef`
476
+ * but removes methods that don't make sense for mutations (like `prefetch`, `value`, etc.).
477
+ *
478
+ * @typeParam TResult - The type of the expected result from the mutation.
479
+ */
480
+ type MutationResourceRef<TResult, TMutation = TResult, TICTX = void, TMethod extends HttpResourceRequest['method'] = HttpResourceRequest['method']> = Omit<QueryResourceRef<TResult>, 'prefetch' | 'value' | 'hasValue' | 'set' | 'update'> & {
481
+ /**
482
+ * Executes the mutation.
483
+ *
484
+ * @param value The request body and any other request parameters to use for the mutation. The `body` property is *required*.
485
+ */
486
+ mutate: (value: Omit<NextRequest<TMethod, TMutation>, 'url'> & {
487
+ url?: string;
488
+ }, ctx?: TICTX) => void;
489
+ /**
490
+ * A signal that holds the current mutation request, or `null` if no mutation is in progress.
491
+ * This can be useful for tracking the state of the mutation or for displaying loading indicators.
492
+ */
493
+ current: Signal<(Omit<NextRequest<TMethod, TMutation>, 'url'> & {
494
+ url?: string;
495
+ }) | null>;
496
+ };
497
+ /**
498
+ * Creates a resource for performing mutations (e.g., POST, PUT, PATCH, DELETE requests).
499
+ * Unlike `queryResource`, `mutationResource` is designed for one-off operations that change data.
500
+ * It does *not* cache responses and does not provide a `value` signal. Instead, it focuses on
501
+ * managing the mutation lifecycle (pending, error, success) and provides callbacks for handling
502
+ * these states.
503
+ *
504
+ * @param request A function that returns the base `HttpResourceRequest` to be made. This
505
+ * function is called reactively. Unlike `queryResource`, the `body` property
506
+ * of the request is provided when `mutate` is called, *not* here. If the
507
+ * function returns `undefined`, the mutation is considered "disabled." All properties,
508
+ * except the body, can be set here.
509
+ * @param options Configuration options for the mutation resource. This includes callbacks
510
+ * for `onMutate`, `onError`, `onSuccess`, and `onSettled`.
511
+ * @typeParam TResult - The type of the expected result from the mutation.
512
+ * @typeParam TRaw - The raw response type from the HTTP request (defaults to TResult).
513
+ * @typeParam TCTX - The type of the context value returned by `onMutate`.
514
+ * @returns A `MutationResourceRef` instance, which provides methods for triggering the mutation
515
+ * and observing its status.
516
+ */
517
+ declare function mutationResource<TResult, TRaw = TResult, TMutation = TResult, TCTX = void, TICTX = TCTX, TMethod extends HttpResourceRequest['method'] = HttpResourceRequest['method']>(request: () => Omit<NextRequest<TMethod, TMutation>, 'body'> | undefined | void, options?: MutationResourceOptions<TResult, TRaw, TMutation, TCTX, TICTX>): MutationResourceRef<TResult, TMutation, TICTX, TMethod>;
518
+
519
+ export { Cache, createCacheInterceptor, createCircuitBreaker, createDedupeRequestsInterceptor, injectQueryCache, mutationResource, noDedupe, provideQueryCache, queryResource };
520
+ export type { MutationResourceOptions, MutationResourceRef, QueryResourceOptions, QueryResourceRef };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mmstack/resource",
3
- "version": "19.2.0",
3
+ "version": "20.0.1",
4
4
  "keywords": [
5
5
  "angular",
6
6
  "signals",
@@ -18,13 +18,13 @@
18
18
  "homepage": "https://github.com/mihajm/mmstack/blob/master/packages/resource",
19
19
  "dependencies": {
20
20
  "uuid": "~11.1.0",
21
- "@mmstack/primitives": "^19.2.1",
22
- "@mmstack/object": "^19.2.0",
21
+ "@mmstack/primitives": "^20.0.1",
22
+ "@mmstack/object": "^20.0.0",
23
23
  "tslib": "^2.3.0"
24
24
  },
25
25
  "peerDependencies": {
26
- "@angular/common": "~19.2.3",
27
- "@angular/core": "~19.2.3",
26
+ "@angular/common": "~20.0.3",
27
+ "@angular/core": "~20.0.3",
28
28
  "rxjs": "~7.8.2"
29
29
  },
30
30
  "sideEffects": false,
@@ -1,92 +0,0 @@
1
- import { type HttpResourceRequest } from '@angular/common/http';
2
- import { Signal, ValueEqualityFn } from '@angular/core';
3
- import { type QueryResourceOptions, type QueryResourceRef } from './query-resource';
4
- /**
5
- * @internal
6
- * Helper type for inferring the request body type based on the HTTP method.
7
- */
8
- type NextRequest<TMethod extends HttpResourceRequest['method'], TMutation> = TMethod extends 'DELETE' | 'delete' ? Omit<HttpResourceRequest, 'body' | 'method'> & {
9
- method?: TMethod;
10
- } : Omit<HttpResourceRequest, 'body' | 'method'> & {
11
- body: TMutation;
12
- method?: TMethod;
13
- };
14
- /**
15
- * Options for configuring a `mutationResource`.
16
- *
17
- * @typeParam TResult - The type of the expected result from the mutation.
18
- * @typeParam TRaw - The raw response type from the HTTP request (defaults to TResult).
19
- * @typeParam TCTX - The type of the context value returned by `onMutate`.
20
- */
21
- export type MutationResourceOptions<TResult, TRaw = TResult, TMutation = TResult, TCTX = void, TICTX = TCTX> = Omit<QueryResourceOptions<TResult, TRaw>, 'equal' | 'onError' | 'keepPrevious' | 'refresh' | 'cache'> & {
22
- /**
23
- * A callback function that is called before the mutation request is made.
24
- * @param value The value being mutated (the `body` of the request).
25
- * @returns An optional context value that will be passed to the `onError`, `onSuccess`, and `onSettled` callbacks. This is useful for storing
26
- * information needed during the mutation lifecycle, such as previous values for optimistic updates or rollback.
27
- */
28
- onMutate?: (value: TMutation, initialCTX?: TICTX) => TCTX;
29
- /**
30
- * A callback function that is called if the mutation request fails.
31
- * @param error The error that occurred.
32
- * @param ctx The context value returned by the `onMutate` callback (or `undefined` if `onMutate` was not provided or returned `undefined`).
33
- */
34
- onError?: (error: unknown, ctx: NoInfer<TCTX>) => void;
35
- /**
36
- * A callback function that is called if the mutation request succeeds.
37
- * @param value The result of the mutation (the parsed response body).
38
- * @param ctx The context value returned by the `onMutate` callback (or `undefined` if `onMutate` was not provided or returned `undefined`).
39
- */
40
- onSuccess?: (value: NoInfer<TResult>, ctx: NoInfer<TCTX>) => void;
41
- /**
42
- * A callback function that is called when the mutation request settles (either succeeds or fails).
43
- * @param ctx The context value returned by the `onMutate` callback (or `undefined` if `onMutate` was not provided or returned `undefined`).
44
- */
45
- onSettled?: (ctx: NoInfer<TCTX>) => void;
46
- equal?: ValueEqualityFn<TMutation>;
47
- };
48
- /**
49
- * Represents a mutation resource created by `mutationResource`. Extends `QueryResourceRef`
50
- * but removes methods that don't make sense for mutations (like `prefetch`, `value`, etc.).
51
- *
52
- * @typeParam TResult - The type of the expected result from the mutation.
53
- */
54
- export type MutationResourceRef<TResult, TMutation = TResult, TICTX = void, TMethod extends HttpResourceRequest['method'] = HttpResourceRequest['method']> = Omit<QueryResourceRef<TResult>, 'prefetch' | 'value' | 'hasValue' | 'set' | 'update'> & {
55
- /**
56
- * Executes the mutation.
57
- *
58
- * @param value The request body and any other request parameters to use for the mutation. The `body` property is *required*.
59
- */
60
- mutate: (value: Omit<NextRequest<TMethod, TMutation>, 'url'> & {
61
- url?: string;
62
- }, ctx?: TICTX) => void;
63
- /**
64
- * A signal that holds the current mutation request, or `null` if no mutation is in progress.
65
- * This can be useful for tracking the state of the mutation or for displaying loading indicators.
66
- */
67
- current: Signal<(Omit<NextRequest<TMethod, TMutation>, 'url'> & {
68
- url?: string;
69
- }) | null>;
70
- };
71
- /**
72
- * Creates a resource for performing mutations (e.g., POST, PUT, PATCH, DELETE requests).
73
- * Unlike `queryResource`, `mutationResource` is designed for one-off operations that change data.
74
- * It does *not* cache responses and does not provide a `value` signal. Instead, it focuses on
75
- * managing the mutation lifecycle (pending, error, success) and provides callbacks for handling
76
- * these states.
77
- *
78
- * @param request A function that returns the base `HttpResourceRequest` to be made. This
79
- * function is called reactively. Unlike `queryResource`, the `body` property
80
- * of the request is provided when `mutate` is called, *not* here. If the
81
- * function returns `undefined`, the mutation is considered "disabled." All properties,
82
- * except the body, can be set here.
83
- * @param options Configuration options for the mutation resource. This includes callbacks
84
- * for `onMutate`, `onError`, `onSuccess`, and `onSettled`.
85
- * @typeParam TResult - The type of the expected result from the mutation.
86
- * @typeParam TRaw - The raw response type from the HTTP request (defaults to TResult).
87
- * @typeParam TCTX - The type of the context value returned by `onMutate`.
88
- * @returns A `MutationResourceRef` instance, which provides methods for triggering the mutation
89
- * and observing its status.
90
- */
91
- export declare function mutationResource<TResult, TRaw = TResult, TMutation = TResult, TCTX = void, TICTX = TCTX, TMethod extends HttpResourceRequest['method'] = HttpResourceRequest['method']>(request: () => Omit<NextRequest<TMethod, TMutation>, 'body'> | undefined | void, options?: MutationResourceOptions<TResult, TRaw, TMutation, TCTX, TICTX>): MutationResourceRef<TResult, TMutation, TICTX, TMethod>;
92
- export {};
@@ -1,3 +0,0 @@
1
- export * from './mutation-resource';
2
- export * from './query-resource';
3
- export * from './util/public_api';