@hyper-fetch/core 9.6.1 → 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.
- package/__tests__/features/adapter/adapter.bindings.progress.spec.ts +120 -0
- package/__tests__/features/adapter/adapter.bindings.spec.ts +4 -6
- package/__tests__/features/adapter/adapter.defaults.spec.ts +87 -0
- package/__tests__/features/adapter/adapter.mapping.spec.ts +257 -0
- package/__tests__/features/cache/cache.lazy-storage.clear.spec.ts +145 -0
- package/__tests__/features/cache/cache.lazy-storage.resilience.spec.ts +667 -0
- package/__tests__/features/cache/cache.scoped-events.spec.ts +183 -0
- package/__tests__/features/cache/cache.semantics.spec.ts +785 -0
- package/__tests__/features/cache/cache.structural-sharing.spec.ts +565 -0
- package/__tests__/features/cache/cache.timing.spec.ts +448 -0
- package/__tests__/features/client/client.clear.spec.ts +313 -0
- package/__tests__/features/client/client.configuration.spec.ts +416 -0
- package/__tests__/features/client/client.hydration.round-trip.spec.ts +324 -0
- package/__tests__/features/client/client.interceptor.spec.ts +54 -45
- package/__tests__/features/client/client.interceptors.pipeline.spec.ts +599 -0
- package/__tests__/features/client/client.user-errors.spec.ts +220 -0
- package/__tests__/features/dispatcher/dispatcher.cleanup.spec.ts +534 -0
- package/__tests__/features/dispatcher/dispatcher.control.spec.ts +381 -0
- package/__tests__/features/dispatcher/dispatcher.modes.spec.ts +527 -0
- package/__tests__/features/dispatcher/dispatcher.offline.spec.ts +278 -0
- package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +35 -12
- package/__tests__/features/dispatcher/dispatcher.reentrancy.spec.ts +309 -0
- package/__tests__/features/dispatcher/dispatcher.response-order.spec.ts +241 -0
- package/__tests__/features/dispatcher/dispatcher.retry-flow.spec.ts +554 -0
- package/__tests__/features/dispatcher/dispatcher.retry-removal.spec.ts +196 -0
- package/__tests__/features/dispatcher/dispatcher.retry.spec.ts +4 -3
- package/__tests__/features/http-adapter/http-adapter.e2e.spec.ts +917 -0
- package/__tests__/features/managers/app/app.manager.events.spec.ts +434 -0
- package/__tests__/features/managers/logger/logger.levels.spec.ts +199 -0
- package/__tests__/features/managers/request/request.manager.abort.spec.ts +449 -0
- package/__tests__/features/mocker/mocker.base.spec.ts +22 -3
- package/__tests__/features/mocker/mocker.errors.spec.ts +99 -0
- package/__tests__/features/mocker/mocker.outcomes.spec.ts +308 -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/plugin/plugin.lifecycle.spec.ts +457 -0
- package/__tests__/features/request/request.async-mapper-removal.spec.ts +138 -0
- package/__tests__/features/request/request.immutability.spec.ts +259 -0
- package/__tests__/features/request/request.inference.spec.ts +269 -0
- package/__tests__/features/request/request.lifecycle.spec.ts +682 -0
- package/__tests__/features/request/request.optimistic-settlement.spec.ts +35 -17
- package/__tests__/features/request/request.optimistic.spec.ts +12 -1
- package/__tests__/features/request/request.values.spec.ts +408 -0
- package/__tests__/features/sdk/sdk.builder.spec.ts +304 -0
- package/__tests__/features/utils/emitter.listeners.spec.ts +202 -0
- package/__tests__/utils/controlled-adapter.utils.ts +119 -0
- package/__tests__/utils/fixtures.utils.ts +193 -0
- package/__tests__/utils/optimistic.utils.ts +124 -0
- package/dist/adapter/adapter.bindings.d.ts.map +1 -1
- package/dist/adapter/adapter.utils.d.ts.map +1 -1
- package/dist/cache/cache.d.ts +12 -1
- package/dist/cache/cache.d.ts.map +1 -1
- package/dist/cache/cache.events.d.ts +20 -6
- package/dist/cache/cache.events.d.ts.map +1 -1
- package/dist/cache/cache.utils.d.ts +1 -0
- package/dist/cache/cache.utils.d.ts.map +1 -1
- package/dist/client/client.d.ts +3 -3
- package/dist/client/client.d.ts.map +1 -1
- package/dist/client/client.utils.d.ts.map +1 -1
- package/dist/dispatcher/dispatcher.d.ts +26 -5
- package/dist/dispatcher/dispatcher.d.ts.map +1 -1
- package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +2787 -1893
- package/dist/index.mjs.map +1 -1
- package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
- package/dist/managers/app/app.manager.d.ts +9 -0
- package/dist/managers/app/app.manager.d.ts.map +1 -1
- package/dist/managers/app/app.manager.utils.d.ts.map +1 -1
- package/dist/managers/logger/logger.manager.d.ts.map +1 -1
- package/dist/managers/request/request.manager.d.ts.map +1 -1
- package/dist/managers/request/request.manager.types.d.ts +2 -0
- package/dist/managers/request/request.manager.types.d.ts.map +1 -1
- package/dist/mocker/mocker.d.ts +1 -1
- package/dist/mocker/mocker.d.ts.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/plugin/plugin.d.ts +2 -0
- package/dist/plugin/plugin.d.ts.map +1 -1
- package/dist/request/request.d.ts +14 -6
- 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/utils/emitter.utils.d.ts.map +1 -1
- package/dist/utils/error.utils.d.ts +17 -0
- package/dist/utils/error.utils.d.ts.map +1 -0
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/adapter/adapter.bindings.ts +46 -18
- package/src/adapter/adapter.utils.ts +47 -7
- package/src/cache/cache.events.ts +24 -8
- package/src/cache/cache.ts +110 -21
- package/src/cache/cache.utils.ts +33 -10
- package/src/client/client.ts +101 -7
- package/src/client/client.utils.ts +10 -4
- package/src/dispatcher/dispatcher.ts +285 -132
- package/src/http-adapter/http-adapter.fetch.ts +15 -3
- package/src/index.ts +4 -0
- package/src/managers/app/app.manager.constants.ts +12 -1
- package/src/managers/app/app.manager.ts +43 -23
- package/src/managers/app/app.manager.utils.ts +8 -4
- package/src/managers/logger/logger.manager.ts +21 -8
- package/src/managers/request/request.manager.ts +7 -1
- package/src/managers/request/request.manager.types.ts +2 -0
- package/src/mocker/mocker.ts +14 -11
- 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/plugin/plugin.ts +6 -0
- package/src/request/request.ts +50 -28
- package/src/request/request.types.ts +41 -1
- package/src/request/request.utils.ts +51 -66
- package/src/utils/emitter.utils.ts +9 -2
- package/src/utils/error.utils.ts +29 -0
- package/src/utils/index.ts +1 -0
- package/tsconfig.json +2 -0
|
@@ -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;
|
|
@@ -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/plugin/plugin.ts
CHANGED
|
@@ -163,6 +163,12 @@ export class Plugin<Client extends ClientInstance = ClientInstance, PluginData =
|
|
|
163
163
|
return this;
|
|
164
164
|
};
|
|
165
165
|
|
|
166
|
+
/** Called when a cache entry is invalidated */
|
|
167
|
+
onCacheItemInvalidate = (callback: PluginMethods<Client>["onCacheItemInvalidate"]) => {
|
|
168
|
+
this.pluginMethods.onCacheItemInvalidate = callback;
|
|
169
|
+
return this;
|
|
170
|
+
};
|
|
171
|
+
|
|
166
172
|
/* -------------------------------------------------------------------------------------------------
|
|
167
173
|
* Adapter lifecycle
|
|
168
174
|
* -----------------------------------------------------------------------------------------------*/
|
package/src/request/request.ts
CHANGED
|
@@ -237,7 +237,7 @@ export class Request<
|
|
|
237
237
|
return this.clone<HasPayload, P extends null ? false : true, HasQuery>({ params });
|
|
238
238
|
};
|
|
239
239
|
|
|
240
|
-
/** Set the request body payload. */
|
|
240
|
+
/** Set the request body payload. Passing `null` removes the payload set before. */
|
|
241
241
|
public setPayload = <P extends Payload>(payload: P) => {
|
|
242
242
|
return this.clone<P extends null ? false : true, HasParams, HasQuery>({
|
|
243
243
|
payload,
|
|
@@ -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<
|
|
@@ -342,20 +350,17 @@ export class Request<
|
|
|
342
350
|
|
|
343
351
|
/** Override the abort key used to cancel this request. */
|
|
344
352
|
public setAbortKey = (abortKey: string) => {
|
|
345
|
-
this.updatedAbortKey
|
|
346
|
-
return this.clone({ abortKey });
|
|
353
|
+
return this.clone({ abortKey, updatedAbortKey: true });
|
|
347
354
|
};
|
|
348
355
|
|
|
349
356
|
/** Override the cache key used to store/retrieve the response. */
|
|
350
357
|
public setCacheKey = (cacheKey: string) => {
|
|
351
|
-
this.updatedCacheKey
|
|
352
|
-
return this.clone({ cacheKey });
|
|
358
|
+
return this.clone({ cacheKey, updatedCacheKey: true });
|
|
353
359
|
};
|
|
354
360
|
|
|
355
361
|
/** Override the query key that identifies this request in the dispatcher queue. */
|
|
356
362
|
public setQueryKey = (queryKey: string) => {
|
|
357
|
-
this.updatedQueryKey
|
|
358
|
-
return this.clone({ queryKey });
|
|
363
|
+
return this.clone({ queryKey, updatedQueryKey: true });
|
|
359
364
|
};
|
|
360
365
|
|
|
361
366
|
/** Enable or disable request deduplication. When enabled, concurrent identical requests share a single response. */
|
|
@@ -468,14 +473,24 @@ export class Request<
|
|
|
468
473
|
private paramsMapper = (params: ParamsType | null | undefined): Endpoint => {
|
|
469
474
|
const { endpoint } = this.requestOptions;
|
|
470
475
|
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
});
|
|
476
|
+
const stringEndpoint = String(endpoint);
|
|
477
|
+
const names = params ? Object.keys(params) : [];
|
|
478
|
+
if (!params || names.length === 0) {
|
|
479
|
+
return stringEndpoint as Endpoint;
|
|
476
480
|
}
|
|
477
481
|
|
|
478
|
-
|
|
482
|
+
// Every `:` segment is replaced once, with the longest matching name. This way `:id` does not eat the beginning
|
|
483
|
+
// of `:idx`, and a value is never parsed again - neither as another param nor as a replacement pattern like `$&`.
|
|
484
|
+
const [start, ...segments] = stringEndpoint.split(":");
|
|
485
|
+
const mapped = segments.map((segment) => {
|
|
486
|
+
const name = names.reduce(
|
|
487
|
+
(longest, current) => (segment.startsWith(current) && current.length > longest.length ? current : longest),
|
|
488
|
+
"",
|
|
489
|
+
);
|
|
490
|
+
return name ? `${params[name]}${segment.slice(name.length)}` : `:${segment}`;
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
return [start, ...mapped].join("") as Endpoint;
|
|
479
494
|
};
|
|
480
495
|
|
|
481
496
|
/** Serialize the request configuration into a plain JSON object for persistence or transfer. */
|
|
@@ -548,12 +563,17 @@ export class Request<
|
|
|
548
563
|
...json,
|
|
549
564
|
...configuration,
|
|
550
565
|
options: configuration?.options || this.options,
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
566
|
+
// A key given by hand is kept by all the next clones, an auto-generated one is generated again
|
|
567
|
+
abortKey: configuration?.abortKey || (this.updatedAbortKey ? this.abortKey : undefined),
|
|
568
|
+
cacheKey: configuration?.cacheKey || (this.updatedCacheKey ? this.cacheKey : undefined),
|
|
569
|
+
queryKey: configuration?.queryKey || (this.updatedQueryKey ? this.queryKey : undefined),
|
|
570
|
+
updatedAbortKey: !!configuration?.abortKey || this.updatedAbortKey,
|
|
571
|
+
updatedCacheKey: !!configuration?.cacheKey || this.updatedCacheKey,
|
|
572
|
+
updatedQueryKey: !!configuration?.queryKey || this.updatedQueryKey,
|
|
554
573
|
endpoint: this.paramsMapper(configuration?.params || this.params),
|
|
555
574
|
queryParams: configuration?.queryParams || this.queryParams,
|
|
556
|
-
|
|
575
|
+
// Falsy payloads like `0`, `false` or an empty string are valid values, `null` removes the payload
|
|
576
|
+
payload: configuration?.payload === null ? undefined : (configuration?.payload ?? this.payload),
|
|
557
577
|
params: (configuration?.params || this.params) as
|
|
558
578
|
| EmptyTypes
|
|
559
579
|
| (Endpoint extends string ? ExtractUrlParams<Endpoint> : never),
|
|
@@ -700,11 +720,8 @@ export class Request<
|
|
|
700
720
|
// Stop listening for aborting
|
|
701
721
|
requestManager.removeAbortController(scopedAbortKey, requestId);
|
|
702
722
|
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
}
|
|
706
|
-
|
|
707
|
-
return response;
|
|
723
|
+
// A throwing response mapper gives the error response, the same way as in `send()`
|
|
724
|
+
return mapResponseForSend(request, response);
|
|
708
725
|
};
|
|
709
726
|
|
|
710
727
|
/**
|
|
@@ -718,7 +735,12 @@ export class Request<
|
|
|
718
735
|
* ```
|
|
719
736
|
*/
|
|
720
737
|
public send: RequestSendType<this> = async (options?: RequestSendOptionsType<this>) => {
|
|
721
|
-
const {
|
|
738
|
+
const {
|
|
739
|
+
dispatcherType: _dispatcherType,
|
|
740
|
+
cachePolicy = "network-only",
|
|
741
|
+
optimistic: _optimistic,
|
|
742
|
+
...configuration
|
|
743
|
+
} = options || {};
|
|
722
744
|
|
|
723
745
|
const request = this.clone(configuration) as unknown as this;
|
|
724
746
|
|