@hyper-fetch/core 9.6.2 → 9.7.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.
Files changed (45) hide show
  1. package/__tests__/features/optimistic/optimistic.concurrency.spec.ts +278 -0
  2. package/__tests__/features/optimistic/optimistic.helpers.spec.ts +307 -0
  3. package/__tests__/features/optimistic/optimistic.matrix.spec.ts +315 -0
  4. package/__tests__/features/optimistic/optimistic.races.spec.ts +270 -0
  5. package/__tests__/features/optimistic/optimistic.random.spec.ts +191 -0
  6. package/__tests__/features/optimistic/optimistic.rollback.spec.ts +1001 -0
  7. package/__tests__/features/optimistic/optimistic.typescript.spec.ts +196 -0
  8. package/__tests__/features/request/request.optimistic.spec.ts +12 -1
  9. package/__tests__/utils/optimistic.utils.ts +124 -0
  10. package/dist/cache/cache.d.ts.map +1 -1
  11. package/dist/client/client.d.ts.map +1 -1
  12. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  13. package/dist/index.d.ts +1 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.mjs +704 -196
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/optimistic/index.d.ts +5 -0
  18. package/dist/optimistic/index.d.ts.map +1 -0
  19. package/dist/optimistic/optimistic.d.ts +67 -0
  20. package/dist/optimistic/optimistic.d.ts.map +1 -0
  21. package/dist/optimistic/optimistic.settlement.d.ts +60 -0
  22. package/dist/optimistic/optimistic.settlement.d.ts.map +1 -0
  23. package/dist/optimistic/optimistic.types.d.ts +109 -0
  24. package/dist/optimistic/optimistic.types.d.ts.map +1 -0
  25. package/dist/optimistic/optimistic.utils.d.ts +29 -0
  26. package/dist/optimistic/optimistic.utils.d.ts.map +1 -0
  27. package/dist/request/request.d.ts +13 -5
  28. package/dist/request/request.d.ts.map +1 -1
  29. package/dist/request/request.types.d.ts +40 -1
  30. package/dist/request/request.types.d.ts.map +1 -1
  31. package/dist/request/request.utils.d.ts.map +1 -1
  32. package/package.json +1 -1
  33. package/src/cache/cache.ts +2 -1
  34. package/src/client/client.ts +2 -0
  35. package/src/dispatcher/dispatcher.ts +13 -0
  36. package/src/index.ts +4 -0
  37. package/src/optimistic/index.ts +4 -0
  38. package/src/optimistic/optimistic.settlement.ts +406 -0
  39. package/src/optimistic/optimistic.ts +162 -0
  40. package/src/optimistic/optimistic.types.ts +175 -0
  41. package/src/optimistic/optimistic.utils.ts +112 -0
  42. package/src/request/request.ts +19 -6
  43. package/src/request/request.types.ts +41 -1
  44. package/src/request/request.utils.ts +31 -54
  45. package/tsconfig.json +2 -0
@@ -0,0 +1,406 @@
1
+ import type { AdapterInstance, ResponseSuccessType, ResponseType } from "adapter";
2
+ import type { CacheValueType } from "cache";
3
+ import type { ClientInstance } from "client";
4
+ import type {
5
+ OptimisticCallbackResult,
6
+ OptimisticCallbackReturnType,
7
+ OptimisticRollbackArgs,
8
+ RequestInstance,
9
+ } from "request";
10
+ import { getRequestKey, scopeKey, stringifyKey } from "request";
11
+ import { throwOutsideLifecycle } from "utils";
12
+
13
+ import { OptimisticOperation } from "./optimistic";
14
+
15
+ /**
16
+ * Settlement of optimistic updates.
17
+ *
18
+ * Every cache key changed by pending mutations has a counter. While it is above zero, fetch responses for the key are
19
+ * not written to the cache, and fetches still running when a mutation on the key settles are marked as stale - they
20
+ * started before the change was confirmed or reverted. Once the last mutation settles and the stale fetches are done,
21
+ * the key is refreshed (invalidated) once, so the server's data replaces the optimistic value.
22
+ */
23
+
24
+ type KeyState = {
25
+ /** Mutations still pending on the key */
26
+ pending: number;
27
+ /** A settled mutation asked for the refresh */
28
+ refresh: boolean;
29
+ /** Request used to invalidate the key */
30
+ request: RequestInstance;
31
+ };
32
+
33
+ type ClientState = {
34
+ keys: Map<string, KeyState>;
35
+ /** Running fetches that started before a mutation on their key settled - request id to storage key */
36
+ staleRequests: Map<string, string>;
37
+ };
38
+
39
+ type AppliedOperation = {
40
+ operation: OptimisticOperation<unknown, RequestInstance>;
41
+ storageKey: string;
42
+ /** Request of the changed entry */
43
+ request: RequestInstance;
44
+ previous: unknown;
45
+ };
46
+
47
+ /** @internal State of one mutation's optimistic updates, from applying them until the mutation settles */
48
+ export type OptimisticPendingType = {
49
+ client: ClientInstance;
50
+ result: OptimisticCallbackResult<unknown>;
51
+ applied: AppliedOperation[];
52
+ /** Every key the operations target, with the request used to refresh it */
53
+ targets: Map<string, RequestInstance>;
54
+ /** Keys changed by the operations - their fetch responses are held back until the mutation settles */
55
+ guarded: Set<string>;
56
+ /** Keys where user code failed - refreshed whatever the outcome */
57
+ failed: Set<string>;
58
+ };
59
+
60
+ /** @internal How the mutation settled */
61
+ export type OptimisticOutcomeType =
62
+ | { type: "success"; response: ResponseType<any, any, AdapterInstance>; request: RequestInstance }
63
+ | ({ type: "rollback" } & OptimisticRollbackArgs<RequestInstance>);
64
+
65
+ const clientStates = new WeakMap<ClientInstance, ClientState>();
66
+
67
+ const getClientState = (client: ClientInstance): ClientState => {
68
+ let state = clientStates.get(client);
69
+ if (!state) {
70
+ state = { keys: new Map(), staleRequests: new Map() };
71
+ clientStates.set(client, state);
72
+ }
73
+ return state;
74
+ };
75
+
76
+ /**
77
+ * Failures of user code (helpers, commits, rollbacks, predicates) are logged and thrown outside of the request
78
+ * lifecycle, like every other user code running in it - the request and the other changes still settle.
79
+ */
80
+ const reportFailure = (client: ClientInstance, title: string, extra: { error: unknown } & Record<string, unknown>) => {
81
+ client.logger.error({ title, type: "system", extra });
82
+ throwOutsideLifecycle(extra.error);
83
+ };
84
+
85
+ const readEntry = (client: ClientInstance, storageKey: string) => {
86
+ return client.cache.get<unknown, unknown>(storageKey);
87
+ };
88
+
89
+ /**
90
+ * Writes the data through the regular cache path, so listeners get one event per change. The entry keeps its
91
+ * timestamps and staleness - an optimistic value doesn't make the entry fresh.
92
+ */
93
+ const writeData = (request: RequestInstance, entry: CacheValueType<unknown, unknown, AdapterInstance>, data: unknown) => {
94
+ const entryRequest = request.clone({ staleTime: entry.staleTime, cacheTime: entry.cacheTime }) as RequestInstance;
95
+ request.client.cache.set(entryRequest, { ...entry, data });
96
+ };
97
+
98
+ /**
99
+ * Cache keys targeted by the operation. `optimistic.all()` matches every entry of the same method and endpoint
100
+ * whatever the query params; a custom cache key matches itself and the keys derived from it (infinite pages).
101
+ */
102
+ const resolveTargets = (client: ClientInstance, operation: OptimisticOperation<unknown, RequestInstance>) => {
103
+ const { target } = operation;
104
+ const targets = new Map<string, RequestInstance>();
105
+
106
+ if (!operation.allVariants) {
107
+ targets.set(scopeKey(target.cacheKey, target.scope), target);
108
+ return targets;
109
+ }
110
+
111
+ const isGeneratedKey = target.cacheKey === getRequestKey(target);
112
+ const prefix = isGeneratedKey
113
+ ? `${stringifyKey(target.method)}_${stringifyKey(target.endpoint)}_`
114
+ : `${target.cacheKey}_`;
115
+
116
+ client.cache.keys().forEach((storageKey) => {
117
+ const entry = client.cache.storage.get<unknown, unknown, AdapterInstance>(storageKey);
118
+ if (!entry || entry.scope !== target.scope) {
119
+ return;
120
+ }
121
+ if (entry.cacheKey === target.cacheKey) {
122
+ targets.set(storageKey, target);
123
+ } else if (entry.cacheKey.startsWith(prefix)) {
124
+ // `setCacheKey` marks the instance it is called on - a clone keeps the user's request untouched
125
+ targets.set(storageKey, target.clone().setCacheKey(entry.cacheKey) as RequestInstance);
126
+ }
127
+ });
128
+
129
+ return targets;
130
+ };
131
+
132
+ /**
133
+ * Runs `.rollback()` / `.commit()` of an operation and writes what it returned. User code can't break the settlement:
134
+ * a throw or a promise is reported and the key gets refreshed.
135
+ */
136
+ const runSettleCallback = (
137
+ pending: OptimisticPendingType,
138
+ { operation, storageKey, request, previous }: AppliedOperation,
139
+ outcome: OptimisticOutcomeType,
140
+ ) => {
141
+ const { client } = pending;
142
+ const entry = readEntry(client, storageKey);
143
+ const isCommit = outcome.type === "success";
144
+ const title = isCommit ? "Optimistic commit failed" : "Optimistic rollback failed";
145
+ const run = (data: unknown) => {
146
+ if (outcome.type === "success") {
147
+ const response = outcome.response as ResponseSuccessType<unknown, AdapterInstance>;
148
+ return operation.onCommit?.({ data, response, request: outcome.request });
149
+ }
150
+ const { type: _type, ...args } = outcome;
151
+ return operation.onRollback?.({ ...args, data, previous });
152
+ };
153
+
154
+ // Entry deleted or cache cleared in the meantime - there is nothing to update
155
+ if (!(isCommit ? operation.onCommit : operation.onRollback) || !entry) {
156
+ return;
157
+ }
158
+
159
+ try {
160
+ const next = run(entry.data);
161
+
162
+ if (next instanceof Promise) {
163
+ next.catch((error: unknown) => reportFailure(client, title, { error, storageKey }));
164
+ throw new TypeError("Optimistic rollback and commit must be synchronous, the returned promise was ignored");
165
+ }
166
+ if (next !== undefined && next !== entry.data) {
167
+ writeData(request, entry, next);
168
+ }
169
+ } catch (error) {
170
+ reportFailure(client, title, { error, storageKey, request: outcome.request });
171
+ pending.failed.add(storageKey);
172
+ }
173
+ };
174
+
175
+ /** Rollback of the hand-written object form - runs once, its failure can't affect the request */
176
+ const runObjectRollback = (pending: OptimisticPendingType, args: OptimisticRollbackArgs<RequestInstance>) => {
177
+ const { client, result } = pending;
178
+ const onFailure = (error: unknown) => {
179
+ reportFailure(client, "Optimistic rollback failed", { error, reason: args.reason, request: args.request });
180
+ };
181
+
182
+ try {
183
+ // Async rollback is not awaited, but its rejection can't stay unhandled
184
+ Promise.resolve(result.rollback?.(args)).catch(onFailure);
185
+ } catch (error) {
186
+ onFailure(error);
187
+ }
188
+ };
189
+
190
+ const runObjectInvalidation = ({ client, result }: OptimisticPendingType, request: RequestInstance) => {
191
+ result.invalidate?.forEach((target) => {
192
+ try {
193
+ client.cache.invalidate(target);
194
+ } catch (error) {
195
+ reportFailure(client, "Optimistic invalidation failed", { error, target, request });
196
+ }
197
+ });
198
+ };
199
+
200
+ /**
201
+ * `rollbackOnError` decides about final errors only - aborted and removed requests are always reverted.
202
+ * A predicate that throws is reported and the change is reverted.
203
+ */
204
+ const shouldRollback = (pending: OptimisticPendingType, outcome: OptimisticRollbackArgs<RequestInstance>) => {
205
+ const { rollbackOnError } = pending.result;
206
+ if (outcome.reason !== "error" || rollbackOnError === undefined || rollbackOnError === true) {
207
+ return true;
208
+ }
209
+ if (rollbackOnError === false) {
210
+ return false;
211
+ }
212
+ try {
213
+ return !!rollbackOnError({ response: outcome.response, request: outcome.request });
214
+ } catch (error) {
215
+ reportFailure(pending.client, "Optimistic rollbackOnError failed", { error, request: outcome.request });
216
+ return true;
217
+ }
218
+ };
219
+
220
+ const getRunningRequestsOnKey = (client: ClientInstance, storageKey: string) => {
221
+ return [...client.fetchDispatcher.getAllRunningRequests(), ...client.submitDispatcher.getAllRunningRequests()].filter(
222
+ ({ request }) => scopeKey(request.cacheKey, request.scope) === storageKey,
223
+ );
224
+ };
225
+
226
+ const hasStaleRequests = (state: ClientState, storageKey: string) => {
227
+ return [...state.staleRequests.values()].includes(storageKey);
228
+ };
229
+
230
+ /** Refreshes the key once nothing pending or stale is left on it */
231
+ const refreshWhenIdle = (client: ClientInstance, state: ClientState, storageKey: string) => {
232
+ const keyState = state.keys.get(storageKey);
233
+ if (!keyState || keyState.pending > 0 || hasStaleRequests(state, storageKey)) {
234
+ return;
235
+ }
236
+ state.keys.delete(storageKey);
237
+ if (keyState.refresh) {
238
+ client.cache.invalidate(keyState.request);
239
+ }
240
+ };
241
+
242
+ const release = (pending: OptimisticPendingType, refresh: boolean) => {
243
+ const { client, targets, failed, guarded } = pending;
244
+ const state = getClientState(client);
245
+
246
+ targets.forEach((request, storageKey) => {
247
+ const keyState = state.keys.get(storageKey);
248
+ const shouldRefresh = refresh || failed.has(storageKey);
249
+
250
+ if (!guarded.has(storageKey)) {
251
+ // Nothing was changed here - refresh together with the mutations still pending on the key, or right away
252
+ if (keyState && shouldRefresh) {
253
+ keyState.refresh = true;
254
+ } else if (shouldRefresh) {
255
+ client.cache.invalidate(request);
256
+ }
257
+ return;
258
+ }
259
+ // State was reset by clearing the client
260
+ if (!keyState) {
261
+ return;
262
+ }
263
+ keyState.pending -= 1;
264
+ keyState.refresh = keyState.refresh || shouldRefresh;
265
+ keyState.request = request;
266
+
267
+ getRunningRequestsOnKey(client, storageKey).forEach(({ requestId }) => {
268
+ state.staleRequests.set(requestId, storageKey);
269
+ });
270
+
271
+ refreshWhenIdle(client, state, storageKey);
272
+ });
273
+ };
274
+
275
+ /**
276
+ * @internal
277
+ * Normalizes what `setOptimistic` or the `optimistic` send option returned into the object form.
278
+ */
279
+ export const getOptimisticResult = (
280
+ value: OptimisticCallbackReturnType<unknown, RequestInstance> | undefined,
281
+ ): OptimisticCallbackResult<unknown> => {
282
+ if (Array.isArray(value)) {
283
+ return { updates: value };
284
+ }
285
+ return value || {};
286
+ };
287
+
288
+ /**
289
+ * @internal
290
+ * Applies the operations of the mutation and registers its target keys as pending. A failing operation is reported,
291
+ * the others still apply.
292
+ */
293
+ export const applyOptimistic = (
294
+ client: ClientInstance,
295
+ result: OptimisticCallbackResult<unknown>,
296
+ ): OptimisticPendingType => {
297
+ const pending: OptimisticPendingType = {
298
+ client,
299
+ result,
300
+ applied: [],
301
+ targets: new Map(),
302
+ guarded: new Set(),
303
+ failed: new Set(),
304
+ };
305
+ const state = getClientState(client);
306
+
307
+ result.updates?.forEach((value) => {
308
+ try {
309
+ if (!(value instanceof OptimisticOperation)) {
310
+ throw new TypeError("Optimistic updates accept operations created with optimistic()");
311
+ }
312
+ const operation = value as OptimisticOperation<unknown, RequestInstance>;
313
+
314
+ resolveTargets(client, operation).forEach((request, storageKey) => {
315
+ pending.targets.set(storageKey, request);
316
+ const entry = readEntry(client, storageKey);
317
+ // No data yet - there is nothing to change and nothing to revert
318
+ if (!entry) {
319
+ return;
320
+ }
321
+ try {
322
+ const next = operation.update(entry.data);
323
+ if (next !== entry.data) {
324
+ writeData(request, entry, next);
325
+ }
326
+ pending.applied.push({ operation, storageKey, request, previous: entry.data });
327
+ pending.guarded.add(storageKey);
328
+ } catch (error) {
329
+ reportFailure(client, "Optimistic update failed", { error, storageKey });
330
+ pending.failed.add(storageKey);
331
+ }
332
+ });
333
+ } catch (error) {
334
+ reportFailure(client, "Optimistic update failed", { error, operation: value });
335
+ }
336
+ });
337
+
338
+ pending.guarded.forEach((storageKey) => {
339
+ const request = pending.targets.get(storageKey) as RequestInstance;
340
+ const keyState = state.keys.get(storageKey) ?? { pending: 0, refresh: false, request };
341
+ keyState.pending += 1;
342
+ state.keys.set(storageKey, keyState);
343
+ });
344
+
345
+ return pending;
346
+ };
347
+
348
+ /**
349
+ * @internal
350
+ * Settles the mutation once. Success runs the commits and invalidations, a final error, abort or queue removal runs the
351
+ * rollbacks in reverse order of application. The targets get refreshed after the last pending mutation on them.
352
+ */
353
+ export const settleOptimistic = (pending: OptimisticPendingType, outcome: OptimisticOutcomeType) => {
354
+ const { result, applied } = pending;
355
+ const canRefresh = result.revalidate !== false;
356
+
357
+ if (outcome.type === "success") {
358
+ applied.forEach((operation) => runSettleCallback(pending, operation, outcome));
359
+ runObjectInvalidation(pending, outcome.request);
360
+ return release(pending, canRefresh);
361
+ }
362
+
363
+ const { type: _type, ...args } = outcome;
364
+ if (!shouldRollback(pending, args)) {
365
+ return release(pending, false);
366
+ }
367
+
368
+ // The latest change is reverted first
369
+ for (let index = applied.length - 1; index >= 0; index -= 1) {
370
+ runSettleCallback(pending, applied[index], outcome);
371
+ }
372
+ runObjectRollback(pending, args);
373
+ return release(pending, canRefresh);
374
+ };
375
+
376
+ /**
377
+ * @internal
378
+ * Stale response guard, called where the dispatcher writes a response to the cache. A response is discarded when a
379
+ * mutation changed its key and is pending, or when the fetch started before the latest such mutation settled - the
380
+ * refresh after the mutation supplies current data. Keys that had no data when the change was applied are not
381
+ * guarded, so a first load is never held back. Manual cache writes don't go through this check.
382
+ */
383
+ export const isStaleOptimisticResponse = (
384
+ client: ClientInstance,
385
+ request: RequestInstance,
386
+ requestId: string,
387
+ ): boolean => {
388
+ const state = clientStates.get(client);
389
+ if (!state) {
390
+ return false;
391
+ }
392
+
393
+ const storageKey = scopeKey(request.cacheKey, request.scope);
394
+ const isMarked = state.staleRequests.delete(requestId);
395
+ const isPending = (state.keys.get(storageKey)?.pending ?? 0) > 0;
396
+ if (isMarked) {
397
+ refreshWhenIdle(client, state, storageKey);
398
+ }
399
+
400
+ return isMarked || isPending;
401
+ };
402
+
403
+ /** @internal Drops the pending state of the client, its mutations will never settle after clearing it */
404
+ export const resetOptimisticState = (client: ClientInstance) => {
405
+ clientStates.delete(client);
406
+ };
@@ -0,0 +1,162 @@
1
+ /* eslint-disable max-params -- increment(match, field, by, options) is the public signature of the helper */
2
+ import type { RequestInstance } from "request";
3
+
4
+ import type {
5
+ OptimisticFactoryType,
6
+ OptimisticInsertOptionsType,
7
+ OptimisticMatchOptionsType,
8
+ OptimisticOperationCommitType,
9
+ OptimisticOperationRollbackType,
10
+ } from "./optimistic.types";
11
+ import type { OptimisticMatcher } from "./optimistic.utils";
12
+ import {
13
+ incrementField,
14
+ incrementItems,
15
+ insertItem,
16
+ patchItems,
17
+ removeItems,
18
+ updateListField,
19
+ } from "./optimistic.utils";
20
+
21
+ /**
22
+ * Callbacks are stored with an erased mutation type - the mutation type is only checked where they are passed in,
23
+ * which keeps operations of a specific mutation assignable to the erased one.
24
+ */
25
+ type OptimisticOperationOptions<Data> = {
26
+ target: RequestInstance;
27
+ allVariants: boolean;
28
+ update: (data: Data) => Data;
29
+ onRollback?: OptimisticOperationRollbackType<Data, RequestInstance>;
30
+ onCommit?: OptimisticOperationCommitType<Data, RequestInstance>;
31
+ };
32
+
33
+ /**
34
+ * One change of one target, built with `optimistic(target)`. Core applies it before the mutation is sent, and runs its
35
+ * `.commit()` on success or its `.rollback()` when the mutation fails, is aborted or removed from the queue.
36
+ * Operations are immutable - `.rollback()` and `.commit()` return a new operation, so one can be reused.
37
+ */
38
+ export class OptimisticOperation<Data, Mutation extends RequestInstance = RequestInstance> {
39
+ /** @internal */
40
+ readonly target: RequestInstance;
41
+ /** @internal */
42
+ readonly allVariants: boolean;
43
+ /** @internal */
44
+ readonly update: (data: Data) => Data;
45
+ /** @internal */
46
+ readonly onRollback?: OptimisticOperationRollbackType<Data, RequestInstance> = undefined;
47
+ /** @internal */
48
+ readonly onCommit?: OptimisticOperationCommitType<Data, RequestInstance> = undefined;
49
+
50
+ constructor(options: OptimisticOperationOptions<Data>) {
51
+ this.target = options.target;
52
+ this.allVariants = options.allVariants;
53
+ this.update = options.update;
54
+ this.onRollback = options.onRollback;
55
+ this.onCommit = options.onCommit;
56
+ }
57
+
58
+ /**
59
+ * Undo of this change, written by hand and run by core when the mutation fails for good, is aborted or removed from
60
+ * the queue. Rollbacks of one mutation run in reverse order of the changes. It receives
61
+ * `{ data, previous, reason, response, request }` and returns the new data; returning nothing leaves the data as it
62
+ * is. Build the result from `data` and use `previous` only to look old values up. Must be synchronous.
63
+ * Without it nothing is undone locally and the target is refetched.
64
+ */
65
+ // Method syntax keeps the mutation type bivariant, so operations typed by a mutation fit erased requests
66
+ rollback(callback: OptimisticOperationRollbackType<Data, Mutation>): OptimisticOperation<Data, Mutation> {
67
+ return new OptimisticOperation({
68
+ target: this.target,
69
+ allVariants: this.allVariants,
70
+ update: this.update,
71
+ onRollback: callback as OptimisticOperationRollbackType<Data, RequestInstance>,
72
+ onCommit: this.onCommit,
73
+ });
74
+ }
75
+
76
+ /**
77
+ * Runs when the mutation succeeds, before the target is refreshed. It receives `{ data, response, request }` and
78
+ * returns the new data, for example to swap a temporary item for the one from the response. Returning nothing leaves
79
+ * the data as it is. Must be synchronous.
80
+ */
81
+ commit(callback: OptimisticOperationCommitType<Data, Mutation>): OptimisticOperation<Data, Mutation> {
82
+ return new OptimisticOperation({
83
+ target: this.target,
84
+ allVariants: this.allVariants,
85
+ update: this.update,
86
+ onRollback: this.onRollback,
87
+ onCommit: callback as OptimisticOperationCommitType<Data, RequestInstance>,
88
+ });
89
+ }
90
+ }
91
+
92
+ type ListUpdate = (list: unknown[]) => unknown[];
93
+
94
+ const createTarget = (target: RequestInstance, allVariants: boolean) => {
95
+ const operation = (update: (data: unknown) => unknown) => {
96
+ return new OptimisticOperation<unknown>({ target, allVariants, update });
97
+ };
98
+
99
+ const createListHelpers = (onList: (update: ListUpdate) => (data: unknown) => unknown) => ({
100
+ patch: (match: OptimisticMatcher, fields: object, options?: OptimisticMatchOptionsType<PropertyKey>) => {
101
+ return operation(onList((list) => patchItems(list, { match, key: options?.key }, fields)));
102
+ },
103
+ insert: (item: unknown, options?: OptimisticInsertOptionsType) => {
104
+ return operation(onList((list) => insertItem(list, item, options)));
105
+ },
106
+ remove: (match: OptimisticMatcher, options?: OptimisticMatchOptionsType<PropertyKey>) => {
107
+ return operation(onList((list) => removeItems(list, { match, key: options?.key })));
108
+ },
109
+ increment: (
110
+ match: OptimisticMatcher,
111
+ field: PropertyKey,
112
+ by: number,
113
+ options?: OptimisticMatchOptionsType<PropertyKey>,
114
+ ) => {
115
+ return operation(onList((list) => incrementItems(list, { match, key: options?.key }, { field, by })));
116
+ },
117
+ });
118
+
119
+ // The target's data is the list itself
120
+ const listHelpers = createListHelpers((update) => (data) => update(data as unknown[]));
121
+
122
+ return {
123
+ ...listHelpers,
124
+ set: (updater: (data: unknown) => unknown) => operation(updater),
125
+ // `increment(field, by)` changes the data, `increment(match, field, by)` the matching list items
126
+ increment: (...args: [PropertyKey, number] | [OptimisticMatcher, PropertyKey, number, object?]) => {
127
+ if (args.length >= 3) {
128
+ const [match, field, by, options] = args as [OptimisticMatcher, PropertyKey, number, object?];
129
+ return listHelpers.increment(match, field, by, options);
130
+ }
131
+ const [field, by] = args as [PropertyKey, number];
132
+ return operation((data) => incrementField(data, field, by));
133
+ },
134
+ list: (field: PropertyKey) => {
135
+ return createListHelpers((update) => (data) => updateListField(data, field, update));
136
+ },
137
+ };
138
+ };
139
+
140
+ const optimisticFactory = (target: RequestInstance) => createTarget(target, false);
141
+ optimisticFactory.all = (target: RequestInstance) => createTarget(target, true);
142
+
143
+ /**
144
+ * Describes an optimistic change of a cached request. Return the operations from `setOptimistic` or pass them with the
145
+ * `optimistic` send option, core applies them, runs `.commit()` / `.rollback()` when the mutation settles and refreshes
146
+ * the targets once the last pending mutation on them is done.
147
+ *
148
+ * - `optimistic(getTodos)` - the entry of this request (its params and query params)
149
+ * - `optimistic.all(getTodos)` - every cached variant of it, whatever the query params (filters, infinite pages)
150
+ *
151
+ * Helpers: `set(updater)`, `patch(match, fields)`, `insert(item, { at })`, `remove(match)`,
152
+ * `increment(field, by)` / `increment(match, field, by)` and `.list("field")` for an array inside an object.
153
+ *
154
+ * @example
155
+ * optimistic(getTodos)
156
+ * .patch(params.todoId, payload)
157
+ * .rollback(({ data, previous }) => {
158
+ * const before = previous.find((todo) => todo.id === params.todoId);
159
+ * return data.map((todo) => (todo.id === params.todoId && before ? before : todo));
160
+ * });
161
+ */
162
+ export const optimistic = optimisticFactory as unknown as OptimisticFactoryType;