@hyper-fetch/core 9.6.2 → 9.8.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.
- package/__tests__/features/adapter/adapter.typescript.spec.ts +34 -0
- package/__tests__/features/adapter/adapter.utils.spec.ts +10 -0
- package/__tests__/features/cache/cache.utils.spec.ts +18 -0
- package/__tests__/features/optimistic/optimistic.concurrency.spec.ts +278 -0
- package/__tests__/features/optimistic/optimistic.helpers.spec.ts +307 -0
- package/__tests__/features/optimistic/optimistic.matrix.spec.ts +315 -0
- package/__tests__/features/optimistic/optimistic.races.spec.ts +270 -0
- package/__tests__/features/optimistic/optimistic.random.spec.ts +191 -0
- package/__tests__/features/optimistic/optimistic.rollback.spec.ts +1001 -0
- package/__tests__/features/optimistic/optimistic.typescript.spec.ts +196 -0
- package/__tests__/features/request/request.cloning.spec.ts +28 -0
- package/__tests__/features/request/request.optimistic.spec.ts +12 -1
- package/__tests__/features/request/request.sending.spec.ts +13 -10
- package/__tests__/type-stress/custom-adapter/custom-adapter.ts +20 -0
- package/__tests__/type-stress/custom-adapter/tsconfig.json +4 -0
- package/__tests__/utils/optimistic.utils.ts +124 -0
- package/dist/cache/cache.d.ts.map +1 -1
- package/dist/client/client.d.ts.map +1 -1
- package/dist/dispatcher/dispatcher.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +578 -70
- package/dist/index.mjs.map +1 -1
- package/dist/optimistic/index.d.ts +5 -0
- package/dist/optimistic/index.d.ts.map +1 -0
- package/dist/optimistic/optimistic.d.ts +67 -0
- package/dist/optimistic/optimistic.d.ts.map +1 -0
- package/dist/optimistic/optimistic.settlement.d.ts +60 -0
- package/dist/optimistic/optimistic.settlement.d.ts.map +1 -0
- package/dist/optimistic/optimistic.types.d.ts +109 -0
- package/dist/optimistic/optimistic.types.d.ts.map +1 -0
- package/dist/optimistic/optimistic.utils.d.ts +29 -0
- package/dist/optimistic/optimistic.utils.d.ts.map +1 -0
- package/dist/request/request.d.ts +13 -5
- package/dist/request/request.d.ts.map +1 -1
- package/dist/request/request.types.d.ts +40 -1
- package/dist/request/request.types.d.ts.map +1 -1
- package/dist/request/request.utils.d.ts.map +1 -1
- package/dist/types/adapter.types.d.ts +12 -1
- package/dist/types/adapter.types.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/cache/cache.ts +2 -1
- package/src/client/client.ts +2 -0
- package/src/dispatcher/dispatcher.ts +13 -0
- package/src/index.ts +1 -0
- package/src/optimistic/index.ts +4 -0
- package/src/optimistic/optimistic.settlement.ts +406 -0
- package/src/optimistic/optimistic.ts +162 -0
- package/src/optimistic/optimistic.types.ts +175 -0
- package/src/optimistic/optimistic.utils.ts +112 -0
- package/src/request/request.ts +19 -6
- package/src/request/request.types.ts +41 -1
- package/src/request/request.utils.ts +30 -54
- package/src/types/adapter.types.ts +42 -25
- 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
|
+
};
|
package/src/request/request.ts
CHANGED
|
@@ -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
|
|
302
|
-
*
|
|
303
|
-
*
|
|
304
|
-
*
|
|
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 {
|
|
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";
|
|
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
|
-
) =>
|
|
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,14 @@ 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 type { OptimisticPendingType } from "optimistic";
|
|
7
|
+
import { applyOptimistic, getOptimisticResult, optimistic, settleOptimistic } from "optimistic";
|
|
6
8
|
import type { ExtractAdapterType, ExtractErrorType } from "types";
|
|
7
|
-
import { runUserCode
|
|
9
|
+
import { runUserCode } from "utils";
|
|
8
10
|
|
|
9
11
|
import type {
|
|
10
12
|
OptimisticCallbackResult,
|
|
11
|
-
|
|
13
|
+
OptimisticSendOptionType,
|
|
12
14
|
ProgressEventType,
|
|
13
15
|
RequestInstance,
|
|
14
16
|
RequestJSON,
|
|
@@ -184,45 +186,6 @@ export const mapResponseForSend = async <Request extends RequestInstance>(
|
|
|
184
186
|
return (mapping || response) as RequestResponseType<Request>;
|
|
185
187
|
};
|
|
186
188
|
|
|
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
189
|
export const sendRequest = async <Request extends RequestInstance>(
|
|
227
190
|
request: Request,
|
|
228
191
|
options?: RequestSendOptionsType<Request>,
|
|
@@ -232,14 +195,26 @@ export const sendRequest = async <Request extends RequestInstance>(
|
|
|
232
195
|
const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);
|
|
233
196
|
|
|
234
197
|
let mutationContext: OptimisticCallbackResult<any> | undefined;
|
|
198
|
+
let pendingOptimistic: OptimisticPendingType | undefined;
|
|
199
|
+
// The per-call option replaces the optimistic callback of the request
|
|
200
|
+
const optimisticSource = (options?.optimistic ?? request.optimistic) as
|
|
201
|
+
| OptimisticSendOptionType<RequestInstance>
|
|
202
|
+
| undefined;
|
|
235
203
|
|
|
236
|
-
if (
|
|
204
|
+
if (optimisticSource) {
|
|
237
205
|
try {
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
206
|
+
const result = Array.isArray(optimisticSource)
|
|
207
|
+
? optimisticSource
|
|
208
|
+
: optimisticSource({
|
|
209
|
+
request,
|
|
210
|
+
client: request.client,
|
|
211
|
+
payload: request.payload,
|
|
212
|
+
params: request.params,
|
|
213
|
+
queryParams: request.queryParams,
|
|
214
|
+
optimistic,
|
|
215
|
+
});
|
|
216
|
+
// Synchronous callbacks change the cache within the send() call, async ones once they resolve
|
|
217
|
+
mutationContext = getOptimisticResult(result instanceof Promise ? await result : result);
|
|
243
218
|
} catch (error) {
|
|
244
219
|
return {
|
|
245
220
|
data: null,
|
|
@@ -253,6 +228,7 @@ export const sendRequest = async <Request extends RequestInstance>(
|
|
|
253
228
|
responseTimestamp: Date.now(),
|
|
254
229
|
};
|
|
255
230
|
}
|
|
231
|
+
pendingOptimistic = applyOptimistic(client, mutationContext);
|
|
256
232
|
}
|
|
257
233
|
|
|
258
234
|
return new Promise<RequestResponseType<Request>>((resolve) => {
|
|
@@ -286,9 +262,9 @@ export const sendRequest = async <Request extends RequestInstance>(
|
|
|
286
262
|
};
|
|
287
263
|
|
|
288
264
|
// Attached ahead of `onBeforeSent`, so listeners added there already observe the settled cache
|
|
289
|
-
const unmountSettlement =
|
|
265
|
+
const unmountSettlement = pendingOptimistic
|
|
290
266
|
? requestManager.events.onResponseById<Request>(requestId, (values) => {
|
|
291
|
-
const
|
|
267
|
+
const pending = pendingOptimistic as OptimisticPendingType;
|
|
292
268
|
const willBeResent = getWillBeResent(values);
|
|
293
269
|
|
|
294
270
|
const settle = (response: ResponseType<any, any, AdapterInstance>) => {
|
|
@@ -298,11 +274,11 @@ export const sendRequest = async <Request extends RequestInstance>(
|
|
|
298
274
|
isSettled = true;
|
|
299
275
|
|
|
300
276
|
if (values.details.isCanceled) {
|
|
301
|
-
|
|
277
|
+
settleOptimistic(pending, { type: "rollback", reason: "abort", response, request });
|
|
302
278
|
} else if (response.success) {
|
|
303
|
-
|
|
279
|
+
settleOptimistic(pending, { type: "success", response, request });
|
|
304
280
|
} else {
|
|
305
|
-
|
|
281
|
+
settleOptimistic(pending, { type: "rollback", reason: "error", response, request });
|
|
306
282
|
}
|
|
307
283
|
};
|
|
308
284
|
|
|
@@ -391,9 +367,9 @@ export const sendRequest = async <Request extends RequestInstance>(
|
|
|
391
367
|
isResolved = true;
|
|
392
368
|
isDelivered = true;
|
|
393
369
|
|
|
394
|
-
if (
|
|
370
|
+
if (pendingOptimistic && !isSettled) {
|
|
395
371
|
isSettled = true;
|
|
396
|
-
|
|
372
|
+
settleOptimistic(pendingOptimistic, { type: "rollback", reason: "removed", request });
|
|
397
373
|
}
|
|
398
374
|
|
|
399
375
|
const enriched = { ...data, mutationContext };
|
|
@@ -30,7 +30,22 @@ export type ExtractAdapterRequestOptionsType<T> =
|
|
|
30
30
|
: RO
|
|
31
31
|
: never;
|
|
32
32
|
|
|
33
|
-
|
|
33
|
+
type UnionToIntersection<Union> = (Union extends unknown ? (value: Union) => void : never) extends (
|
|
34
|
+
value: infer Intersection,
|
|
35
|
+
) => void
|
|
36
|
+
? Intersection
|
|
37
|
+
: never;
|
|
38
|
+
|
|
39
|
+
/** `true` for a union of adapters. A single adapter type equals its own intersection, which is checked by identity. */
|
|
40
|
+
type IsAdapterUnion<AdapterType> = [AdapterType] extends [UnionToIntersection<AdapterType>] ? false : true;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Special type only for selecting appropriate AdapterType union version (check FirebaseAdapterType).
|
|
44
|
+
*
|
|
45
|
+
* A single adapter is returned as it is. Picking it with `Extract` would compare the whole `Adapter` class structurally,
|
|
46
|
+
* reaching through the client and request types - deep enough to hit the instantiation limit of tsgo in
|
|
47
|
+
* `createRequest()()` for custom adapters.
|
|
48
|
+
*/
|
|
34
49
|
export type ExtractUnionAdapter<
|
|
35
50
|
AdapterType extends AdapterInstance,
|
|
36
51
|
Values extends {
|
|
@@ -43,28 +58,30 @@ export type ExtractUnionAdapter<
|
|
|
43
58
|
defaultQueryParams?: any;
|
|
44
59
|
},
|
|
45
60
|
> =
|
|
46
|
-
|
|
47
|
-
AdapterType
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
61
|
+
IsAdapterUnion<AdapterType> extends false
|
|
62
|
+
? AdapterType
|
|
63
|
+
: Extract<
|
|
64
|
+
AdapterType,
|
|
65
|
+
Adapter<
|
|
66
|
+
Values["options"],
|
|
67
|
+
Values["method"],
|
|
68
|
+
Values["status"],
|
|
69
|
+
Values["extra"],
|
|
70
|
+
Values["queryParams"],
|
|
71
|
+
Values["defaultQueryParams"],
|
|
72
|
+
Values["endpointType"]
|
|
73
|
+
>
|
|
74
|
+
> extends AdapterInstance
|
|
75
|
+
? Extract<
|
|
76
|
+
AdapterType,
|
|
77
|
+
Adapter<
|
|
78
|
+
Values["options"],
|
|
79
|
+
Values["method"],
|
|
80
|
+
Values["status"],
|
|
81
|
+
Values["extra"],
|
|
82
|
+
Values["queryParams"],
|
|
83
|
+
Values["defaultQueryParams"],
|
|
84
|
+
Values["endpointType"]
|
|
85
|
+
>
|
|
68
86
|
>
|
|
69
|
-
|
|
70
|
-
: never;
|
|
87
|
+
: never;
|
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"],
|