@mmstack/resource 20.2.6 → 20.2.7

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