@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,175 @@
1
+ /* eslint-disable max-params -- increment(match, field, by, options) is the public signature of the helper */
2
+ import type { ResponseSuccessType } from "adapter";
3
+ import type { OptimisticRollbackArgs, ParamType, RequestInstance } from "request";
4
+ import type {
5
+ EmptyTypes,
6
+ ExtractAdapterType,
7
+ ExtractHasParamsType,
8
+ ExtractParamsType,
9
+ ExtractResponseType,
10
+ } from "types";
11
+
12
+ import type { OptimisticOperation } from "./optimistic";
13
+
14
+ // Keys
15
+
16
+ /** Keys of `T` holding numbers, the fields `increment` can change */
17
+ export type OptimisticNumberKeys<T> = {
18
+ [K in keyof T]-?: NonNullable<T[K]> extends number ? K : never;
19
+ }[keyof T];
20
+
21
+ /** Keys of `T` holding arrays, the fields `.list()` can target */
22
+ export type OptimisticListKeys<T> = {
23
+ [K in keyof T]-?: NonNullable<T[K]> extends readonly unknown[] ? K : never;
24
+ }[keyof T];
25
+
26
+ /** Item of the array held in the `K` field of `T` */
27
+ export type OptimisticListItem<T, K extends keyof T> = NonNullable<T[K]> extends readonly (infer Item)[] ? Item : never;
28
+
29
+ /** The key compared with a plain `match` value when no `key` is given */
30
+ export type OptimisticDefaultKey<Item> = "id" extends keyof Item ? "id" : never;
31
+
32
+ /**
33
+ * Selects the list items a helper changes.
34
+ * - A predicate: `(todo) => todo.id === todoId`
35
+ * - A plain value compared with the item's `key` field (`id` by default). Numbers and strings match each other, so a
36
+ * route param `"1"` matches the id `1`.
37
+ */
38
+ export type OptimisticMatchType<Item, Key extends keyof Item> =
39
+ | ((item: Item) => boolean)
40
+ | ([Key] extends [never] ? never : Item[Key] extends ParamType ? ParamType : Item[Key]);
41
+
42
+ export type OptimisticMatchOptionsType<Key> = {
43
+ /** Field compared with a plain `match` value, `id` by default */
44
+ key?: Key;
45
+ };
46
+
47
+ export type OptimisticInsertOptionsType = {
48
+ /** Where the item goes: `"start"`, `"end"` (default) or an index */
49
+ at?: "start" | "end" | number;
50
+ };
51
+
52
+ // Callbacks
53
+
54
+ /**
55
+ * Argument of `.rollback()`.
56
+ * - `data` - the target's data as it is now, after other mutations and server responses
57
+ * - `previous` - the target's data just before this operation was applied, for looking up old values
58
+ * - `reason` - why the change is reverted: `"error"`, `"abort"` or `"removed"` (from the queue)
59
+ * - `response` / `request` - the mutation's failed response (absent for `"removed"`) and the mutation request
60
+ */
61
+ export type OptimisticOperationRollbackArgs<Data, Mutation extends RequestInstance> = OptimisticRollbackArgs<Mutation> & {
62
+ data: Data;
63
+ previous: Data;
64
+ };
65
+
66
+ /**
67
+ * Argument of `.commit()`.
68
+ * - `data` - the target's data as it is now
69
+ * - `response` / `request` - the mutation's successful response and the mutation request
70
+ */
71
+ export type OptimisticOperationCommitArgs<Data, Mutation extends RequestInstance> = {
72
+ data: Data;
73
+ response: ResponseSuccessType<ExtractResponseType<Mutation>, ExtractAdapterType<Mutation>>;
74
+ request: Mutation;
75
+ };
76
+
77
+ /*
78
+ * The callbacks are declared as methods - their parameters stay bivariant, so an operation typed by a specific
79
+ * mutation is accepted where the erased request type is expected (the request type depends on them through
80
+ * `setOptimistic`).
81
+ */
82
+
83
+ /**
84
+ * Returns the new data of the target. Returning nothing leaves the data as it is. Must be synchronous.
85
+ */
86
+ export type OptimisticOperationRollbackType<Data, Mutation extends RequestInstance> = {
87
+ bivarianceHack(args: OptimisticOperationRollbackArgs<Data, Mutation>): Data | void;
88
+ }["bivarianceHack"];
89
+
90
+ /**
91
+ * Returns the new data of the target. Returning nothing leaves the data as it is. Must be synchronous.
92
+ */
93
+ export type OptimisticOperationCommitType<Data, Mutation extends RequestInstance> = {
94
+ bivarianceHack(args: OptimisticOperationCommitArgs<Data, Mutation>): Data | void;
95
+ }["bivarianceHack"];
96
+
97
+ // Targets
98
+
99
+ type OptimisticTargetError = {
100
+ "Target request needs params": "Call setParams() on the target before passing it to optimistic()";
101
+ };
102
+
103
+ type RequiresParams<Target> =
104
+ ExtractHasParamsType<Target> extends true ? false : ExtractParamsType<Target> extends EmptyTypes ? false : true;
105
+
106
+ /** A target request, rejected at compile time while its endpoint params are not set */
107
+ export type OptimisticTargetRequestType<Target extends RequestInstance> = Target &
108
+ (RequiresParams<Target> extends true ? OptimisticTargetError : unknown);
109
+
110
+ /** Helpers changing the items of a list - the target's data or an array field of it */
111
+ export type OptimisticListTargetType<Data, Item, Mutation extends RequestInstance> = {
112
+ /** Merges `fields` into every matching item */
113
+ patch: <Key extends keyof Item = OptimisticDefaultKey<Item>>(
114
+ match: OptimisticMatchType<Item, Key>,
115
+ fields: Partial<Item>,
116
+ options?: OptimisticMatchOptionsType<Key>,
117
+ ) => OptimisticOperation<Data, Mutation>;
118
+ /** Adds the item, at the end unless `at` says otherwise */
119
+ insert: (item: Item, options?: OptimisticInsertOptionsType) => OptimisticOperation<Data, Mutation>;
120
+ /** Removes every matching item */
121
+ remove: <Key extends keyof Item = OptimisticDefaultKey<Item>>(
122
+ match: OptimisticMatchType<Item, Key>,
123
+ options?: OptimisticMatchOptionsType<Key>,
124
+ ) => OptimisticOperation<Data, Mutation>;
125
+ /** Adds `by` to a number field of every matching item */
126
+ increment: <Field extends OptimisticNumberKeys<Item>, Key extends keyof Item = OptimisticDefaultKey<Item>>(
127
+ match: OptimisticMatchType<Item, Key>,
128
+ field: Field,
129
+ by: number,
130
+ options?: OptimisticMatchOptionsType<Key>,
131
+ ) => OptimisticOperation<Data, Mutation>;
132
+ };
133
+
134
+ /** Helpers changing a target whose data is an object */
135
+ export type OptimisticEntryTargetType<Data, Mutation extends RequestInstance> = {
136
+ /** Adds `by` to a number field of the data */
137
+ increment: <Field extends OptimisticNumberKeys<Data>>(field: Field, by: number) => OptimisticOperation<Data, Mutation>;
138
+ /** Targets the array held in `field`, for the list helpers */
139
+ list: <Field extends OptimisticListKeys<Data>>(
140
+ field: Field,
141
+ ) => OptimisticListTargetType<Data, OptimisticListItem<Data, Field>, Mutation>;
142
+ };
143
+
144
+ /**
145
+ * Helpers available for a target. The list helpers exist when the target's data is an array; for a list inside an
146
+ * object name it first with `.list("field")`.
147
+ */
148
+ export type OptimisticTargetType<Data, Mutation extends RequestInstance> = {
149
+ /** Replaces the data with the updater's result */
150
+ set: (updater: (data: Data) => Data) => OptimisticOperation<Data, Mutation>;
151
+ } & (0 extends 1 & Data
152
+ ? // Untyped data - every helper is available
153
+ OptimisticListTargetType<Data, any, Mutation> & OptimisticEntryTargetType<Data, Mutation>
154
+ : [Data] extends [readonly (infer Item)[]]
155
+ ? OptimisticListTargetType<Data, Item, Mutation>
156
+ : OptimisticEntryTargetType<Data, Mutation>);
157
+
158
+ /**
159
+ * Builds optimistic operations. `optimistic(request)` changes the request's cache entry,
160
+ * `optimistic.all(request)` every cached variant of it, whatever the query params (filters, infinite pages).
161
+ */
162
+ export type OptimisticFactoryType<Mutation extends RequestInstance = RequestInstance> = {
163
+ <Target extends RequestInstance>(
164
+ target: OptimisticTargetRequestType<Target>,
165
+ ): OptimisticTargetType<ExtractResponseType<Target>, Mutation>;
166
+ all: <Target extends RequestInstance>(
167
+ target: OptimisticTargetRequestType<Target>,
168
+ ) => OptimisticTargetType<ExtractResponseType<Target>, Mutation>;
169
+ };
170
+
171
+ /** Operations returned from `setOptimistic` or passed with the `optimistic` send option */
172
+ export type OptimisticUpdatesType<Mutation extends RequestInstance = RequestInstance> = OptimisticOperation<
173
+ any,
174
+ Mutation
175
+ >[];
@@ -0,0 +1,112 @@
1
+ import type { OptimisticInsertOptionsType } from "./optimistic.types";
2
+
3
+ /** Erased match - a predicate or a plain value compared with the `key` field */
4
+ export type OptimisticMatcher = ((item: any) => boolean) | unknown;
5
+
6
+ /** Selects list items: the match and the field a plain value is compared with */
7
+ export type OptimisticSelector = { match: OptimisticMatcher; key?: PropertyKey };
8
+
9
+ type Item = Record<PropertyKey, unknown>;
10
+
11
+ const isComparableId = (value: unknown): value is string | number =>
12
+ typeof value === "string" || typeof value === "number";
13
+
14
+ /**
15
+ * Tells if the item is selected by the match. Plain values are compared with the `key` field of the item, numbers and
16
+ * strings match each other the same way route params do (`"1"` matches `1`).
17
+ */
18
+ export const isOptimisticMatch = (item: unknown, match: OptimisticMatcher, key: PropertyKey = "id"): boolean => {
19
+ if (typeof match === "function") {
20
+ return !!match(item);
21
+ }
22
+ if (item === null || typeof item !== "object") {
23
+ return false;
24
+ }
25
+ const value = (item as Item)[key];
26
+ if (Object.is(value, match)) {
27
+ return true;
28
+ }
29
+ return isComparableId(value) && isComparableId(match) && String(value) === String(match);
30
+ };
31
+
32
+ const assertList = (list: unknown): unknown[] => {
33
+ if (!Array.isArray(list)) {
34
+ throw new TypeError("Optimistic list helpers need an array, use .list(field) for an array inside an object");
35
+ }
36
+ return list;
37
+ };
38
+
39
+ const assertEntry = (data: unknown): Item => {
40
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
41
+ throw new TypeError("Optimistic increment(field, by) needs an object, use increment(match, field, by) on a list");
42
+ }
43
+ return data as Item;
44
+ };
45
+
46
+ const addToField = (item: Item, field: PropertyKey, by: number): Item => {
47
+ const value = item[field];
48
+ return { ...item, [field]: (typeof value === "number" ? value : 0) + by };
49
+ };
50
+
51
+ /**
52
+ * Maps the matching items. The list keeps its reference when nothing matched, so unchanged data produces no write.
53
+ */
54
+ const mapMatching = (list: unknown, { match, key }: OptimisticSelector, map: (item: Item) => Item): unknown[] => {
55
+ const items = assertList(list);
56
+ let changed = false;
57
+ const next = items.map((item) => {
58
+ if (!isOptimisticMatch(item, match, key)) {
59
+ return item;
60
+ }
61
+ changed = true;
62
+ return map(item as Item);
63
+ });
64
+ return changed ? next : items;
65
+ };
66
+
67
+ export const patchItems = (list: unknown, selector: OptimisticSelector, fields: object): unknown[] => {
68
+ return mapMatching(list, selector, (item) => ({ ...item, ...fields }));
69
+ };
70
+
71
+ export const insertItem = (list: unknown, item: unknown, options?: OptimisticInsertOptionsType): unknown[] => {
72
+ const items = assertList(list);
73
+ const at = options?.at ?? "end";
74
+ if (at === "start") {
75
+ return [item, ...items];
76
+ }
77
+ if (at === "end") {
78
+ return [...items, item];
79
+ }
80
+ const next = [...items];
81
+ next.splice(at, 0, item);
82
+ return next;
83
+ };
84
+
85
+ export const removeItems = (list: unknown, { match, key }: OptimisticSelector): unknown[] => {
86
+ const items = assertList(list);
87
+ const next = items.filter((item) => !isOptimisticMatch(item, match, key));
88
+ return next.length === items.length ? items : next;
89
+ };
90
+
91
+ export const incrementItems = (
92
+ list: unknown,
93
+ selector: OptimisticSelector,
94
+ { field, by }: { field: PropertyKey; by: number },
95
+ ): unknown[] => {
96
+ return mapMatching(list, selector, (item) => addToField(item, field, by));
97
+ };
98
+
99
+ export const incrementField = (data: unknown, field: PropertyKey, by: number): Item => {
100
+ return addToField(assertEntry(data), field, by);
101
+ };
102
+
103
+ /**
104
+ * Runs a list helper on the array held in `field`. A missing list counts as empty, the object keeps its reference when
105
+ * the list did not change.
106
+ */
107
+ export const updateListField = (data: unknown, field: PropertyKey, update: (list: unknown[]) => unknown[]): Item => {
108
+ const entry = assertEntry(data);
109
+ const list = entry[field] ?? [];
110
+ const next = update(assertList(list));
111
+ return next === list ? entry : { ...entry, [field]: next };
112
+ };
@@ -298,12 +298,20 @@ export class Request<
298
298
 
299
299
  /**
300
300
  * Configure optimistic update behavior for this request.
301
- * The callback runs before the request is sent and receives the request, client, and payload.
302
- * Return `context` (available in lifecycle callbacks), `rollback` (called automatically once on
303
- * failure, abort or queue removal), and `invalidate` (requests invalidated on success).
304
- * Both run for every way of sending the request, not only inside of framework hooks.
301
+ * The callback runs before the request is sent and receives `{ request, client, payload, params, queryParams,
302
+ * optimistic }`. A synchronous callback changes the cache within the `send()` call.
303
+ *
304
+ * Return an array of changes built with `optimistic()` - core applies them, runs their `.commit()` on success or
305
+ * `.rollback()` on final failure, abort or queue removal, and refreshes the targets after the last pending mutation
306
+ * on them. Or return an object with `updates`, `context` (available in lifecycle callbacks as `mutationContext`),
307
+ * `rollback` (called once on failure, abort or queue removal), `invalidate` (requests invalidated on success),
308
+ * `rollbackOnError` and `revalidate`.
309
+ * Everything runs for every way of sending the request, not only inside of framework hooks.
310
+ *
311
+ * @example
312
+ * toggleTodo.setOptimistic(({ params, payload }) => [optimistic(getTodos).patch(params.todoId, payload)]);
305
313
  */
306
- public setOptimistic = <Ctx>(callback: OptimisticCallback<this, Ctx>) => {
314
+ public setOptimistic = <Ctx = undefined>(callback: OptimisticCallback<this, Ctx>) => {
307
315
  const cloned = this.clone<HasPayload, HasParams, HasQuery>();
308
316
  cloned.optimistic = callback as OptimisticCallback<RequestInstance, any>;
309
317
  return cloned as unknown as Request<
@@ -727,7 +735,12 @@ export class Request<
727
735
  * ```
728
736
  */
729
737
  public send: RequestSendType<this> = async (options?: RequestSendOptionsType<this>) => {
730
- const { dispatcherType: _dispatcherType, cachePolicy = "network-only", ...configuration } = options || {};
738
+ const {
739
+ dispatcherType: _dispatcherType,
740
+ cachePolicy = "network-only",
741
+ optimistic: _optimistic,
742
+ ...configuration
743
+ } = options || {};
731
744
 
732
745
  const request = this.clone(configuration) as unknown as this;
733
746
 
@@ -1,6 +1,7 @@
1
1
  import type { RequestResponseType, ResponseSuccessType, ResponseErrorType } from "adapter";
2
2
  import type { ClientInstance } from "client";
3
3
  import type { RequestEventType, RequestProgressEventType, RequestResponseEventType } from "managers";
4
+ import type { OptimisticFactoryType, OptimisticUpdatesType } from "optimistic/optimistic.types";
4
5
  /* eslint-disable @typescript-eslint/no-shadow */
5
6
  import type {
6
7
  NullableKeys,
@@ -372,6 +373,11 @@ export type RequestDynamicSendOptionsType<Request extends RequestInstance> = Omi
372
373
  > & {
373
374
  dispatcherType?: "auto" | "fetch" | "submit";
374
375
  cachePolicy?: RequestCachePolicyType;
376
+ /**
377
+ * Optimistic update of this call - `optimistic()` operations or a callback like the one of `setOptimistic`.
378
+ * Replaces the request's own optimistic callback for this call.
379
+ */
380
+ optimistic?: OptimisticSendOptionType<Request>;
375
381
  };
376
382
 
377
383
  // Request making
@@ -429,6 +435,15 @@ export type OptimisticCallbackArgs<Req extends RequestInstance> = {
429
435
  request: Req;
430
436
  client: Req["client"];
431
437
  payload: ExtractPayloadType<Req>;
438
+ /** Endpoint params of the mutation */
439
+ params: ExtractParamsType<Req>;
440
+ /** Query params of the mutation */
441
+ queryParams: ExtractQueryParamsType<Req>;
442
+ /**
443
+ * The `optimistic()` builder with `.commit()` and `.rollback()` typed by this mutation's response.
444
+ * Same as the exported `optimistic`, whose callbacks receive an erased mutation type.
445
+ */
446
+ optimistic: OptimisticFactoryType<Req>;
432
447
  };
433
448
 
434
449
  /**
@@ -441,17 +456,42 @@ export type OptimisticRollbackArgs<Req extends RequestInstance> =
441
456
  | { reason: "error" | "abort"; response: RequestResponseType<Req>; request: Req }
442
457
  | { reason: "removed"; response?: undefined; request: Req };
443
458
 
459
+ /**
460
+ * Object form of the optimistic result. All fields are optional.
461
+ */
444
462
  export type OptimisticCallbackResult<Ctx, Req extends RequestInstance = RequestInstance> = {
463
+ /** Value delivered as `mutationContext` to the lifecycle callbacks */
445
464
  context?: Ctx;
465
+ /** Operations built with `optimistic()`, applied in order and reverted in reverse order */
466
+ updates?: OptimisticUpdatesType;
446
467
  /** Runs once when the request settles without success, also outside of any framework */
447
468
  rollback?: (args: OptimisticRollbackArgs<Req>) => void;
448
469
  /** Requests invalidated in the cache once the request succeeds */
449
470
  invalidate?: RequestInstance[];
471
+ /**
472
+ * Decides if a final error reverts the change (`true` by default). Aborted and removed requests are always reverted.
473
+ * With `false` the change stays, no rollback runs and nothing is refreshed.
474
+ */
475
+ rollbackOnError?: boolean | ((args: { response: RequestResponseType<Req>; request: Req }) => boolean);
476
+ /** Refresh the targets of `updates` once the last pending mutation on them settles (`true` by default) */
477
+ revalidate?: boolean;
450
478
  };
451
479
 
480
+ /**
481
+ * What an optimistic callback returns: an array of `optimistic()` operations, or the object form.
482
+ */
483
+ export type OptimisticCallbackReturnType<Ctx, Req extends RequestInstance = RequestInstance> =
484
+ | OptimisticUpdatesType
485
+ | OptimisticCallbackResult<Ctx, Req>;
486
+
452
487
  export type OptimisticCallback<Req extends RequestInstance, Ctx = undefined> = (
453
488
  args: OptimisticCallbackArgs<Req>,
454
- ) => OptimisticCallbackResult<Ctx, Req> | Promise<OptimisticCallbackResult<Ctx, Req>>;
489
+ ) => OptimisticCallbackReturnType<Ctx, Req> | Promise<OptimisticCallbackReturnType<Ctx, Req>>;
490
+
491
+ /**
492
+ * Per-call optimistic update - operations or a callback like the one of `setOptimistic`. Replaces the request's own.
493
+ */
494
+ export type OptimisticSendOptionType<Req extends RequestInstance> = OptimisticUpdatesType | OptimisticCallback<Req, any>;
455
495
 
456
496
  // Mappers
457
497
 
@@ -3,12 +3,15 @@ import type { AdapterInstance, ProgressType, RequestResponseType, ResponseType }
3
3
  import { SAFE_HTTP_METHODS } from "constants/http.constants";
4
4
  import type { Dispatcher } from "dispatcher";
5
5
  import type { RequestResponseEventType } from "managers";
6
+ import { optimistic } from "optimistic/optimistic";
7
+ import type { OptimisticPendingType } from "optimistic/optimistic.settlement";
8
+ import { applyOptimistic, getOptimisticResult, settleOptimistic } from "optimistic/optimistic.settlement";
6
9
  import type { ExtractAdapterType, ExtractErrorType } from "types";
7
- import { runUserCode, throwOutsideLifecycle } from "utils";
10
+ import { runUserCode } from "utils";
8
11
 
9
12
  import type {
10
13
  OptimisticCallbackResult,
11
- OptimisticRollbackArgs,
14
+ OptimisticSendOptionType,
12
15
  ProgressEventType,
13
16
  RequestInstance,
14
17
  RequestJSON,
@@ -184,45 +187,6 @@ export const mapResponseForSend = async <Request extends RequestInstance>(
184
187
  return (mapping || response) as RequestResponseType<Request>;
185
188
  };
186
189
 
187
- /**
188
- * Rollback is user code running in the middle of the response handling, its failure can't affect the request
189
- */
190
- const rollbackOptimistic = (
191
- optimistic: OptimisticCallbackResult<any>,
192
- args: OptimisticRollbackArgs<RequestInstance>,
193
- ): void => {
194
- const logFailure = (error: unknown) => {
195
- args.request.client.logger.error({
196
- title: "Optimistic rollback failed",
197
- type: "system",
198
- extra: { error, reason: args.reason, request: args.request },
199
- });
200
- throwOutsideLifecycle(error);
201
- };
202
-
203
- try {
204
- // Async rollback is not awaited, but its rejection can't stay unhandled
205
- Promise.resolve(optimistic.rollback?.(args)).catch(logFailure);
206
- } catch (error) {
207
- logFailure(error);
208
- }
209
- };
210
-
211
- const invalidateOptimistic = (optimistic: OptimisticCallbackResult<any>, request: RequestInstance): void => {
212
- optimistic.invalidate?.forEach((target) => {
213
- try {
214
- request.client.cache.invalidate(target);
215
- } catch (error) {
216
- request.client.logger.error({
217
- title: "Optimistic invalidation failed",
218
- type: "system",
219
- extra: { error, target, request },
220
- });
221
- throwOutsideLifecycle(error);
222
- }
223
- });
224
- };
225
-
226
190
  export const sendRequest = async <Request extends RequestInstance>(
227
191
  request: Request,
228
192
  options?: RequestSendOptionsType<Request>,
@@ -232,14 +196,26 @@ export const sendRequest = async <Request extends RequestInstance>(
232
196
  const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);
233
197
 
234
198
  let mutationContext: OptimisticCallbackResult<any> | undefined;
199
+ let pendingOptimistic: OptimisticPendingType | undefined;
200
+ // The per-call option replaces the optimistic callback of the request
201
+ const optimisticSource = (options?.optimistic ?? request.optimistic) as
202
+ | OptimisticSendOptionType<RequestInstance>
203
+ | undefined;
235
204
 
236
- if (request.optimistic) {
205
+ if (optimisticSource) {
237
206
  try {
238
- mutationContext = await request.optimistic({
239
- request,
240
- client: request.client,
241
- payload: request.payload,
242
- });
207
+ const result = Array.isArray(optimisticSource)
208
+ ? optimisticSource
209
+ : optimisticSource({
210
+ request,
211
+ client: request.client,
212
+ payload: request.payload,
213
+ params: request.params,
214
+ queryParams: request.queryParams,
215
+ optimistic,
216
+ });
217
+ // Synchronous callbacks change the cache within the send() call, async ones once they resolve
218
+ mutationContext = getOptimisticResult(result instanceof Promise ? await result : result);
243
219
  } catch (error) {
244
220
  return {
245
221
  data: null,
@@ -253,6 +229,7 @@ export const sendRequest = async <Request extends RequestInstance>(
253
229
  responseTimestamp: Date.now(),
254
230
  };
255
231
  }
232
+ pendingOptimistic = applyOptimistic(client, mutationContext);
256
233
  }
257
234
 
258
235
  return new Promise<RequestResponseType<Request>>((resolve) => {
@@ -286,9 +263,9 @@ export const sendRequest = async <Request extends RequestInstance>(
286
263
  };
287
264
 
288
265
  // Attached ahead of `onBeforeSent`, so listeners added there already observe the settled cache
289
- const unmountSettlement = mutationContext
266
+ const unmountSettlement = pendingOptimistic
290
267
  ? requestManager.events.onResponseById<Request>(requestId, (values) => {
291
- const optimistic = mutationContext as OptimisticCallbackResult<any>;
268
+ const pending = pendingOptimistic as OptimisticPendingType;
292
269
  const willBeResent = getWillBeResent(values);
293
270
 
294
271
  const settle = (response: ResponseType<any, any, AdapterInstance>) => {
@@ -298,11 +275,11 @@ export const sendRequest = async <Request extends RequestInstance>(
298
275
  isSettled = true;
299
276
 
300
277
  if (values.details.isCanceled) {
301
- rollbackOptimistic(optimistic, { reason: "abort", response, request });
278
+ settleOptimistic(pending, { type: "rollback", reason: "abort", response, request });
302
279
  } else if (response.success) {
303
- invalidateOptimistic(optimistic, request);
280
+ settleOptimistic(pending, { type: "success", response, request });
304
281
  } else {
305
- rollbackOptimistic(optimistic, { reason: "error", response, request });
282
+ settleOptimistic(pending, { type: "rollback", reason: "error", response, request });
306
283
  }
307
284
  };
308
285
 
@@ -391,9 +368,9 @@ export const sendRequest = async <Request extends RequestInstance>(
391
368
  isResolved = true;
392
369
  isDelivered = true;
393
370
 
394
- if (mutationContext && !isSettled) {
371
+ if (pendingOptimistic && !isSettled) {
395
372
  isSettled = true;
396
- rollbackOptimistic(mutationContext, { reason: "removed", request });
373
+ settleOptimistic(pendingOptimistic, { type: "rollback", reason: "removed", request });
397
374
  }
398
375
 
399
376
  const enriched = { ...data, mutationContext };
package/tsconfig.json CHANGED
@@ -19,6 +19,8 @@
19
19
  "managers/*": ["./src/managers/*"],
20
20
  "mocker": ["./src/mocker"],
21
21
  "mocker/*": ["./src/mocker/*"],
22
+ "optimistic": ["./src/optimistic"],
23
+ "optimistic/*": ["./src/optimistic/*"],
22
24
  "plugin": ["./src/plugin"],
23
25
  "plugin/*": ["./src/plugin/*"],
24
26
  "request": ["./src/request"],