@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,307 @@
|
|
|
1
|
+
import { Client } from "client";
|
|
2
|
+
import { optimistic } from "optimistic";
|
|
3
|
+
import type { OptimisticOperation } from "optimistic";
|
|
4
|
+
|
|
5
|
+
type Todo = { id: number; title: string; done: boolean; likes: number; tags?: string[] };
|
|
6
|
+
type Feed = { cursor: string | null; total: number; items: Todo[]; meta: { pages: number } };
|
|
7
|
+
|
|
8
|
+
const createTodo = (id: number, extra: Partial<Todo> = {}): Todo => ({
|
|
9
|
+
id,
|
|
10
|
+
title: `todo-${id}`,
|
|
11
|
+
done: false,
|
|
12
|
+
likes: 0,
|
|
13
|
+
...extra,
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Operations are pure descriptions - `update` is the transformation core applies to the cached data
|
|
18
|
+
*/
|
|
19
|
+
const apply = <Data>(operation: OptimisticOperation<Data, any>, data: Data): Data => operation.update(data);
|
|
20
|
+
|
|
21
|
+
describe("Optimistic [ Helpers ]", () => {
|
|
22
|
+
const client = new Client({ url: "shared-base-url" });
|
|
23
|
+
const getTodos = client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos" });
|
|
24
|
+
const getFeed = client.createRequest<{ response: Feed }>()({ endpoint: "/feed" });
|
|
25
|
+
const getTodo = client.createRequest<{ response: Todo }>()({ endpoint: "/todos/:todoId" });
|
|
26
|
+
|
|
27
|
+
let list: Todo[];
|
|
28
|
+
let feed: Feed;
|
|
29
|
+
|
|
30
|
+
beforeEach(() => {
|
|
31
|
+
list = [createTodo(1), createTodo(2), createTodo(3)];
|
|
32
|
+
feed = { cursor: "c1", total: 3, items: list, meta: { pages: 1 } };
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
describe("when using set", () => {
|
|
36
|
+
it("should replace the data with the updater result", () => {
|
|
37
|
+
const result = apply(
|
|
38
|
+
optimistic(getTodo.setParams({ todoId: 1 })).set((todo) => ({ ...todo, title: "changed" })),
|
|
39
|
+
list[0],
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
expect(result).toStrictEqual({ ...list[0], title: "changed" });
|
|
43
|
+
expect(list[0].title).toBe("todo-1");
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it("should pass the data of a list target", () => {
|
|
47
|
+
const updater = vi.fn((todos: Todo[]) => todos.slice(1));
|
|
48
|
+
const result = apply(optimistic(getTodos).set(updater), list);
|
|
49
|
+
|
|
50
|
+
expect(updater).toHaveBeenCalledWith(list);
|
|
51
|
+
expect(result).toStrictEqual([list[1], list[2]]);
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
describe("when using patch", () => {
|
|
56
|
+
it("should patch the item matched by id value", () => {
|
|
57
|
+
const result = apply(optimistic(getTodos).patch(2, { done: true }), list);
|
|
58
|
+
|
|
59
|
+
expect(result).toStrictEqual([list[0], { ...list[1], done: true }, list[2]]);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it("should match a string id with a number id like route params do", () => {
|
|
63
|
+
const result = apply(optimistic(getTodos).patch("2", { done: true }), list);
|
|
64
|
+
|
|
65
|
+
expect(result[1].done).toBeTrue();
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("should patch the items matched by predicate", () => {
|
|
69
|
+
const result = apply(
|
|
70
|
+
optimistic(getTodos).patch((todo) => todo.id !== 2, { done: true }),
|
|
71
|
+
list,
|
|
72
|
+
);
|
|
73
|
+
|
|
74
|
+
expect(result.map((todo) => todo.done)).toStrictEqual([true, false, true]);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("should match by custom key", () => {
|
|
78
|
+
const result = apply(optimistic(getTodos).patch("todo-3", { done: true }, { key: "title" }), list);
|
|
79
|
+
|
|
80
|
+
expect(result.map((todo) => todo.done)).toStrictEqual([false, false, true]);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it("should keep unchanged items referentially equal", () => {
|
|
84
|
+
const result = apply(optimistic(getTodos).patch(2, { done: true }), list);
|
|
85
|
+
|
|
86
|
+
expect(result[0]).toBe(list[0]);
|
|
87
|
+
expect(result[2]).toBe(list[2]);
|
|
88
|
+
expect(result[1]).not.toBe(list[1]);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it("should return the same list when nothing matched", () => {
|
|
92
|
+
expect(apply(optimistic(getTodos).patch(99, { done: true }), list)).toBe(list);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it("should return the same empty list", () => {
|
|
96
|
+
const empty: Todo[] = [];
|
|
97
|
+
expect(apply(optimistic(getTodos).patch(1, { done: true }), empty)).toBe(empty);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("should patch several matches", () => {
|
|
101
|
+
const duplicated = [createTodo(1), createTodo(1, { title: "twin" }), createTodo(2)];
|
|
102
|
+
const result = apply(optimistic(getTodos).patch(1, { likes: 5 }), duplicated);
|
|
103
|
+
|
|
104
|
+
expect(result.map((todo) => todo.likes)).toStrictEqual([5, 5, 0]);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it("should replace nested values instead of merging them deeply", () => {
|
|
108
|
+
const tagged = [createTodo(1, { tags: ["a", "b"] })];
|
|
109
|
+
const result = apply(optimistic(getTodos).patch(1, { tags: ["c"] }), tagged);
|
|
110
|
+
|
|
111
|
+
expect(result[0].tags).toStrictEqual(["c"]);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it("should patch the items of a list field", () => {
|
|
115
|
+
const result = apply(optimistic(getFeed).list("items").patch(1, { done: true }), feed);
|
|
116
|
+
|
|
117
|
+
expect(result.items[0].done).toBeTrue();
|
|
118
|
+
expect(result.meta).toBe(feed.meta);
|
|
119
|
+
expect(result.cursor).toBe("c1");
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it("should return the same object when nothing in a list field matched", () => {
|
|
123
|
+
expect(apply(optimistic(getFeed).list("items").patch(99, { done: true }), feed)).toBe(feed);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it("should skip primitives and nulls when matching by value", () => {
|
|
127
|
+
const mixed = [null, 1, createTodo(1)] as unknown as Todo[];
|
|
128
|
+
const result = apply(optimistic(getTodos).patch(1, { done: true }), mixed);
|
|
129
|
+
|
|
130
|
+
expect(result[0]).toBeNull();
|
|
131
|
+
expect(result[1]).toBe(1);
|
|
132
|
+
expect(result[2].done).toBeTrue();
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
describe("when using insert", () => {
|
|
137
|
+
it("should add the item at the end by default", () => {
|
|
138
|
+
const result = apply(optimistic(getTodos).insert(createTodo(4)), list);
|
|
139
|
+
|
|
140
|
+
expect(result.map((todo) => todo.id)).toStrictEqual([1, 2, 3, 4]);
|
|
141
|
+
expect(list).toHaveLength(3);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it("should add the item at the start", () => {
|
|
145
|
+
const result = apply(optimistic(getTodos).insert(createTodo(4), { at: "start" }), list);
|
|
146
|
+
|
|
147
|
+
expect(result.map((todo) => todo.id)).toStrictEqual([4, 1, 2, 3]);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it("should add the item at the end explicitly", () => {
|
|
151
|
+
const result = apply(optimistic(getTodos).insert(createTodo(4), { at: "end" }), list);
|
|
152
|
+
|
|
153
|
+
expect(result.map((todo) => todo.id)).toStrictEqual([1, 2, 3, 4]);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("should add the item at the index", () => {
|
|
157
|
+
const result = apply(optimistic(getTodos).insert(createTodo(4), { at: 1 }), list);
|
|
158
|
+
|
|
159
|
+
expect(result.map((todo) => todo.id)).toStrictEqual([1, 4, 2, 3]);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it("should add the item to an empty list", () => {
|
|
163
|
+
expect(apply(optimistic(getTodos).insert(createTodo(4)), [])).toStrictEqual([createTodo(4)]);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("should add the item to a list field", () => {
|
|
167
|
+
const result = apply(optimistic(getFeed).list("items").insert(createTodo(4), { at: "start" }), feed);
|
|
168
|
+
|
|
169
|
+
expect(result.items.map((todo) => todo.id)).toStrictEqual([4, 1, 2, 3]);
|
|
170
|
+
expect(result.total).toBe(3);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it("should create a missing list field", () => {
|
|
174
|
+
const noItems = { ...feed, items: undefined } as unknown as Feed;
|
|
175
|
+
const result = apply(optimistic(getFeed).list("items").insert(createTodo(4)), noItems);
|
|
176
|
+
|
|
177
|
+
expect(result.items).toStrictEqual([createTodo(4)]);
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
describe("when using remove", () => {
|
|
182
|
+
it("should remove the item matched by id value", () => {
|
|
183
|
+
const result = apply(optimistic(getTodos).remove(2), list);
|
|
184
|
+
|
|
185
|
+
expect(result).toStrictEqual([list[0], list[2]]);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it("should remove the items matched by predicate", () => {
|
|
189
|
+
const result = apply(
|
|
190
|
+
optimistic(getTodos).remove((todo) => todo.id > 1),
|
|
191
|
+
list,
|
|
192
|
+
);
|
|
193
|
+
|
|
194
|
+
expect(result).toStrictEqual([list[0]]);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it("should remove by custom key", () => {
|
|
198
|
+
expect(apply(optimistic(getTodos).remove("todo-1", { key: "title" }), list)).toStrictEqual([list[1], list[2]]);
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it("should return the same list when nothing matched", () => {
|
|
202
|
+
expect(apply(optimistic(getTodos).remove(99), list)).toBe(list);
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it("should remove from a list field", () => {
|
|
206
|
+
const result = apply(optimistic(getFeed).list("items").remove(1), feed);
|
|
207
|
+
|
|
208
|
+
expect(result.items.map((todo) => todo.id)).toStrictEqual([2, 3]);
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
it("should keep the object of a missing list field", () => {
|
|
212
|
+
const noItems = { ...feed, items: undefined } as unknown as Feed;
|
|
213
|
+
expect(apply(optimistic(getFeed).list("items").remove(1), noItems)).toBe(noItems);
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
describe("when using increment", () => {
|
|
218
|
+
it("should increment a field of the data", () => {
|
|
219
|
+
const result = apply(optimistic(getFeed).increment("total", -1), feed);
|
|
220
|
+
|
|
221
|
+
expect(result.total).toBe(2);
|
|
222
|
+
expect(result.items).toBe(feed.items);
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
it("should start from zero when the field is missing", () => {
|
|
226
|
+
const noTotal = { ...feed, total: undefined } as unknown as Feed;
|
|
227
|
+
expect(apply(optimistic(getFeed).increment("total", 2), noTotal).total).toBe(2);
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
it("should increment a field of the matched items", () => {
|
|
231
|
+
const result = apply(optimistic(getTodos).increment(2, "likes", 3), list);
|
|
232
|
+
|
|
233
|
+
expect(result.map((todo) => todo.likes)).toStrictEqual([0, 3, 0]);
|
|
234
|
+
expect(result[0]).toBe(list[0]);
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
it("should increment by predicate and custom key", () => {
|
|
238
|
+
const byPredicate = apply(
|
|
239
|
+
optimistic(getTodos).increment((todo) => todo.id < 3, "likes", 1),
|
|
240
|
+
list,
|
|
241
|
+
);
|
|
242
|
+
const byKey = apply(optimistic(getTodos).increment("todo-3", "likes", 1, { key: "title" }), list);
|
|
243
|
+
|
|
244
|
+
expect(byPredicate.map((todo) => todo.likes)).toStrictEqual([1, 1, 0]);
|
|
245
|
+
expect(byKey.map((todo) => todo.likes)).toStrictEqual([0, 0, 1]);
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
it("should return the same list when nothing matched", () => {
|
|
249
|
+
expect(apply(optimistic(getTodos).increment(99, "likes", 1), list)).toBe(list);
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
it("should increment items of a list field", () => {
|
|
253
|
+
const result = apply(optimistic(getFeed).list("items").increment(1, "likes", 2), feed);
|
|
254
|
+
|
|
255
|
+
expect(result.items[0].likes).toBe(2);
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
describe("when the data has the wrong shape", () => {
|
|
260
|
+
it("should throw from list helpers on an object", () => {
|
|
261
|
+
const operation = optimistic(getTodos).patch(1, { done: true });
|
|
262
|
+
|
|
263
|
+
expect(() => apply(operation, feed as unknown as Todo[])).toThrow(TypeError);
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
it("should throw from increment(field, by) on a list", () => {
|
|
267
|
+
const operation = optimistic(getFeed).increment("total", 1);
|
|
268
|
+
|
|
269
|
+
expect(() => apply(operation, list as unknown as Feed)).toThrow(TypeError);
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
it("should throw from a list field that is not an array", () => {
|
|
273
|
+
const broken = { ...feed, items: "nope" } as unknown as Feed;
|
|
274
|
+
|
|
275
|
+
expect(() => apply(optimistic(getFeed).list("items").insert(createTodo(4)), broken)).toThrow(TypeError);
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
it("should throw from a list field of null data", () => {
|
|
279
|
+
expect(() => apply(optimistic(getFeed).list("items").insert(createTodo(4)), null as unknown as Feed)).toThrow(
|
|
280
|
+
TypeError,
|
|
281
|
+
);
|
|
282
|
+
});
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
describe("when chaining", () => {
|
|
286
|
+
it("should return new operations from rollback and commit", () => {
|
|
287
|
+
const base = optimistic(getTodos).remove(1);
|
|
288
|
+
const rollback = () => {};
|
|
289
|
+
const commit = () => {};
|
|
290
|
+
const withRollback = base.rollback(rollback);
|
|
291
|
+
const withBoth = withRollback.commit(commit);
|
|
292
|
+
|
|
293
|
+
expect(base.onRollback).toBeUndefined();
|
|
294
|
+
expect(withRollback.onRollback).toBe(rollback);
|
|
295
|
+
expect(withRollback.onCommit).toBeUndefined();
|
|
296
|
+
expect(withBoth.onRollback).toBe(rollback);
|
|
297
|
+
expect(withBoth.onCommit).toBe(commit);
|
|
298
|
+
expect(withBoth.commit(commit).rollback(rollback).update).toBe(base.update);
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
it("should target the request or all of its variants", () => {
|
|
302
|
+
expect(optimistic(getTodos).remove(1).allVariants).toBeFalse();
|
|
303
|
+
expect(optimistic.all(getTodos).remove(1).allVariants).toBeTrue();
|
|
304
|
+
expect(optimistic.all(getTodos).remove(1).target).toBe(getTodos);
|
|
305
|
+
});
|
|
306
|
+
});
|
|
307
|
+
});
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { createHttpMockingServer } from "@hyper-fetch/testing";
|
|
2
|
+
import { waitFor } from "@testing-library/dom";
|
|
3
|
+
|
|
4
|
+
import { Client } from "client";
|
|
5
|
+
import type { RequestResponseEventType } from "managers";
|
|
6
|
+
import { optimistic } from "optimistic";
|
|
7
|
+
import type { RequestInstance } from "request";
|
|
8
|
+
import { scopeKey } from "request";
|
|
9
|
+
import { readCache, seedCache } from "../../utils/optimistic.utils";
|
|
10
|
+
|
|
11
|
+
const { resetMocks, startServer, stopServer, mockRequest } = createHttpMockingServer();
|
|
12
|
+
|
|
13
|
+
const INITIAL = ["server"];
|
|
14
|
+
const HELPER_ITEM = "helper";
|
|
15
|
+
const OBJECT_ITEM = "object";
|
|
16
|
+
|
|
17
|
+
type Form = "helpers" | "object" | "combined";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Every form adds its own item to the list - helpers through `insert`, the object form by hand - and reverts it.
|
|
21
|
+
*/
|
|
22
|
+
const createSetup = (form: Form) => {
|
|
23
|
+
const client = new Client({ url: "shared-base-url" });
|
|
24
|
+
const list = client.createRequest<{ response: string[] }>()({ endpoint: "/list" });
|
|
25
|
+
seedCache(client, list, INITIAL);
|
|
26
|
+
|
|
27
|
+
const helperRollback = vi.fn(({ data }: { data: string[] }) => data.filter((item) => item !== HELPER_ITEM));
|
|
28
|
+
const objectRollback = vi.fn(() => {
|
|
29
|
+
client.cache.update(list, (prev) => ({ data: (prev?.data ?? []).filter((item) => item !== OBJECT_ITEM) }));
|
|
30
|
+
});
|
|
31
|
+
const invalidate = vi.spyOn(client.cache, "invalidate");
|
|
32
|
+
|
|
33
|
+
const mutation = client
|
|
34
|
+
.createRequest<{ response: { ok: boolean } }>()({ endpoint: "/mutation", method: "POST" })
|
|
35
|
+
.setOptimistic(() => {
|
|
36
|
+
const updates = [optimistic(list).insert(HELPER_ITEM).rollback(helperRollback)];
|
|
37
|
+
if (form === "helpers") {
|
|
38
|
+
return updates;
|
|
39
|
+
}
|
|
40
|
+
client.cache.update(list, (prev) => ({ data: [...(prev?.data ?? []), OBJECT_ITEM] }));
|
|
41
|
+
return {
|
|
42
|
+
context: { form },
|
|
43
|
+
rollback: objectRollback,
|
|
44
|
+
invalidate: [list],
|
|
45
|
+
updates: form === "combined" ? updates : undefined,
|
|
46
|
+
};
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const responses: RequestResponseEventType<RequestInstance>[] = [];
|
|
50
|
+
client.requestManager.events.onResponse((values) => {
|
|
51
|
+
responses.push(values);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const queryKey = scopeKey(mutation.queryKey, mutation.scope);
|
|
55
|
+
const abortKey = scopeKey(mutation.abortKey, mutation.scope);
|
|
56
|
+
const read = () => readCache<string[]>(client, list);
|
|
57
|
+
|
|
58
|
+
return { client, list, mutation, helperRollback, objectRollback, invalidate, responses, queryKey, abortKey, read };
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
type Setup = ReturnType<typeof createSetup>;
|
|
62
|
+
type Mutation = Setup["mutation"];
|
|
63
|
+
|
|
64
|
+
const optimisticList = (form: Form) => {
|
|
65
|
+
if (form === "helpers") {
|
|
66
|
+
return [...INITIAL, HELPER_ITEM];
|
|
67
|
+
}
|
|
68
|
+
if (form === "object") {
|
|
69
|
+
return [...INITIAL, OBJECT_ITEM];
|
|
70
|
+
}
|
|
71
|
+
return [...INITIAL, OBJECT_ITEM, HELPER_ITEM];
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/** Invalidations of the list: the object form's `invalidate` on success, the helpers' refresh after every settle */
|
|
75
|
+
const expectedInvalidations = (form: Form, success: boolean, rolledBack: boolean) => {
|
|
76
|
+
const objectInvalidation = form !== "helpers" && success ? 1 : 0;
|
|
77
|
+
const refresh = form !== "object" && (success || rolledBack) ? 1 : 0;
|
|
78
|
+
return objectInvalidation + refresh;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const waitForResponses = async (setup: Setup, count: number) => {
|
|
82
|
+
await waitFor(() => {
|
|
83
|
+
expect(setup.responses).toHaveLength(count);
|
|
84
|
+
});
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const goOfflineOnFirstAttempt = (setup: Setup) => {
|
|
88
|
+
let isFirstAttempt = true;
|
|
89
|
+
return {
|
|
90
|
+
onRequestStart: () => {
|
|
91
|
+
if (isFirstAttempt) {
|
|
92
|
+
isFirstAttempt = false;
|
|
93
|
+
setup.client.appManager.setOnline(false);
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
type Outcome = {
|
|
100
|
+
name: string;
|
|
101
|
+
build?: (mutation: Mutation) => Mutation;
|
|
102
|
+
arrange: (setup: Setup, request: Mutation) => Record<string, unknown> | void;
|
|
103
|
+
drive?: (setup: Setup, request: Mutation, form: Form) => Promise<void>;
|
|
104
|
+
settled?: (setup: Setup) => Promise<void>;
|
|
105
|
+
success: boolean;
|
|
106
|
+
rollback?: "error" | "abort" | "removed";
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const outcomes: Outcome[] = [
|
|
110
|
+
{
|
|
111
|
+
name: "success",
|
|
112
|
+
arrange: (_, request) => mockRequest(request, { data: { ok: true } }),
|
|
113
|
+
success: true,
|
|
114
|
+
},
|
|
115
|
+
{
|
|
116
|
+
name: "final error",
|
|
117
|
+
arrange: (_, request) => mockRequest(request, { status: 400 }),
|
|
118
|
+
success: false,
|
|
119
|
+
rollback: "error",
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
name: "abort",
|
|
123
|
+
arrange: (_, request) => {
|
|
124
|
+
mockRequest(request, { delay: 100 });
|
|
125
|
+
return { onRequestStart: () => request.abort() };
|
|
126
|
+
},
|
|
127
|
+
success: false,
|
|
128
|
+
rollback: "abort",
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
name: "queue removal",
|
|
132
|
+
arrange: (setup, request) => {
|
|
133
|
+
mockRequest(request);
|
|
134
|
+
setup.client.submitDispatcher.stop(setup.queryKey);
|
|
135
|
+
return {
|
|
136
|
+
onBeforeSent: ({ requestId }: { requestId: string }) => {
|
|
137
|
+
queueMicrotask(() => setup.client.submitDispatcher.delete(setup.queryKey, requestId, setup.abortKey));
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
},
|
|
141
|
+
success: false,
|
|
142
|
+
rollback: "removed",
|
|
143
|
+
},
|
|
144
|
+
{
|
|
145
|
+
name: "retry then success",
|
|
146
|
+
build: (mutation) => mutation.setRetry(1).setRetryTime(10),
|
|
147
|
+
arrange: (setup, request) => {
|
|
148
|
+
mockRequest(request, { status: 400 });
|
|
149
|
+
const unmount = setup.client.requestManager.events.onResponse(() => {
|
|
150
|
+
unmount();
|
|
151
|
+
// While the retry is scheduled the change stays
|
|
152
|
+
expect(setup.helperRollback).not.toHaveBeenCalled();
|
|
153
|
+
expect(setup.objectRollback).not.toHaveBeenCalled();
|
|
154
|
+
mockRequest(request, { data: { ok: true } });
|
|
155
|
+
});
|
|
156
|
+
},
|
|
157
|
+
success: true,
|
|
158
|
+
},
|
|
159
|
+
{
|
|
160
|
+
name: "retry then error",
|
|
161
|
+
build: (mutation) => mutation.setRetry(1).setRetryTime(10),
|
|
162
|
+
arrange: (setup, request) => {
|
|
163
|
+
mockRequest(request, { status: 400 });
|
|
164
|
+
const unmount = setup.client.requestManager.events.onResponse(() => {
|
|
165
|
+
unmount();
|
|
166
|
+
mockRequest(request, { status: 500 });
|
|
167
|
+
});
|
|
168
|
+
},
|
|
169
|
+
success: false,
|
|
170
|
+
rollback: "error",
|
|
171
|
+
},
|
|
172
|
+
{
|
|
173
|
+
name: "offline then success",
|
|
174
|
+
arrange: (setup, request) => {
|
|
175
|
+
mockRequest(request, { status: 400, delay: 30 });
|
|
176
|
+
return goOfflineOnFirstAttempt(setup);
|
|
177
|
+
},
|
|
178
|
+
drive: async (setup, request, form) => {
|
|
179
|
+
await waitForResponses(setup, 1);
|
|
180
|
+
expect(setup.read()).toStrictEqual(optimisticList(form));
|
|
181
|
+
expect(setup.invalidate).not.toHaveBeenCalled();
|
|
182
|
+
mockRequest(request, { data: { ok: true } });
|
|
183
|
+
setup.client.appManager.setOnline(true);
|
|
184
|
+
},
|
|
185
|
+
success: true,
|
|
186
|
+
},
|
|
187
|
+
{
|
|
188
|
+
name: "offline then error",
|
|
189
|
+
arrange: (setup, request) => {
|
|
190
|
+
mockRequest(request, { status: 400, delay: 30 });
|
|
191
|
+
return goOfflineOnFirstAttempt(setup);
|
|
192
|
+
},
|
|
193
|
+
drive: async (setup, request, form) => {
|
|
194
|
+
await waitForResponses(setup, 1);
|
|
195
|
+
expect(setup.read()).toStrictEqual(optimisticList(form));
|
|
196
|
+
mockRequest(request, { status: 500 });
|
|
197
|
+
setup.client.appManager.setOnline(true);
|
|
198
|
+
},
|
|
199
|
+
success: false,
|
|
200
|
+
rollback: "error",
|
|
201
|
+
},
|
|
202
|
+
];
|
|
203
|
+
|
|
204
|
+
const entryPoints = [
|
|
205
|
+
{
|
|
206
|
+
name: "send()",
|
|
207
|
+
run: (request: Mutation, options: Record<string, unknown>) => {
|
|
208
|
+
return request.send(options).then((result) => ({ result, observed: null }));
|
|
209
|
+
},
|
|
210
|
+
},
|
|
211
|
+
{
|
|
212
|
+
name: "$hooks",
|
|
213
|
+
run: (request: Mutation, options: Record<string, unknown>, setup: Setup) => {
|
|
214
|
+
let observed: { list?: string[]; rollbacks: number; invalidations: number } | null = null;
|
|
215
|
+
const observe = () => {
|
|
216
|
+
observed = {
|
|
217
|
+
list: setup.read(),
|
|
218
|
+
rollbacks: setup.helperRollback.mock.calls.length + setup.objectRollback.mock.calls.length,
|
|
219
|
+
invalidations: setup.invalidate.mock.calls.length,
|
|
220
|
+
};
|
|
221
|
+
};
|
|
222
|
+
request.$hooks.onResponse(observe);
|
|
223
|
+
request.$hooks.onRemove(observe);
|
|
224
|
+
return request.send(options).then((result) => ({ result, observed }));
|
|
225
|
+
},
|
|
226
|
+
},
|
|
227
|
+
];
|
|
228
|
+
|
|
229
|
+
const forms: Form[] = ["helpers", "object", "combined"];
|
|
230
|
+
|
|
231
|
+
describe("Optimistic [ Settlement matrix ]", () => {
|
|
232
|
+
beforeAll(() => {
|
|
233
|
+
startServer();
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
afterEach(() => {
|
|
237
|
+
resetMocks();
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
afterAll(() => {
|
|
241
|
+
stopServer();
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
describe.each(entryPoints)("when using $name", ({ name: entryPoint, run }) => {
|
|
245
|
+
describe.each(forms)("when using the %s form", (form) => {
|
|
246
|
+
it.each(outcomes)("should settle $name", async ({ build, arrange, drive, settled, success, rollback }) => {
|
|
247
|
+
const setup = createSetup(form);
|
|
248
|
+
const request = build?.(setup.mutation) ?? setup.mutation;
|
|
249
|
+
const options = arrange(setup, request) ?? {};
|
|
250
|
+
|
|
251
|
+
const pending = run(request, options, setup);
|
|
252
|
+
expect(setup.read()).toStrictEqual(optimisticList(form));
|
|
253
|
+
|
|
254
|
+
await drive?.(setup, request, form);
|
|
255
|
+
const { result, observed } = await pending;
|
|
256
|
+
await settled?.(setup);
|
|
257
|
+
|
|
258
|
+
const expectedList = rollback ? INITIAL : optimisticList(form);
|
|
259
|
+
const expectedRollbacks = rollback ? { helper: form !== "object" ? 1 : 0, object: form !== "helpers" ? 1 : 0 } : null;
|
|
260
|
+
const invalidations = expectedInvalidations(form, success, !!rollback);
|
|
261
|
+
|
|
262
|
+
expect(result.success).toBe(success);
|
|
263
|
+
expect(setup.read()).toStrictEqual(expectedList);
|
|
264
|
+
expect(setup.helperRollback).toHaveBeenCalledTimes(expectedRollbacks?.helper ?? 0);
|
|
265
|
+
expect(setup.objectRollback).toHaveBeenCalledTimes(expectedRollbacks?.object ?? 0);
|
|
266
|
+
expect(setup.invalidate).toHaveBeenCalledTimes(invalidations);
|
|
267
|
+
if (invalidations) {
|
|
268
|
+
expect(setup.invalidate).toHaveBeenCalledWith(setup.list);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
if (rollback && form !== "object") {
|
|
272
|
+
expect(setup.helperRollback.mock.calls[0][0]).toHaveProperty("reason", rollback);
|
|
273
|
+
}
|
|
274
|
+
if (rollback && form !== "helpers") {
|
|
275
|
+
expect(setup.objectRollback.mock.calls[0]).toStrictEqual([expect.objectContaining({ reason: rollback })]);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Lifecycle listeners already see the settled cache
|
|
279
|
+
if (entryPoint === "$hooks") {
|
|
280
|
+
expect(observed).toStrictEqual({
|
|
281
|
+
list: expectedList,
|
|
282
|
+
rollbacks: (expectedRollbacks?.helper ?? 0) + (expectedRollbacks?.object ?? 0),
|
|
283
|
+
invalidations,
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
});
|
|
287
|
+
});
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
describe("when the optimistic callback is synchronous", () => {
|
|
291
|
+
it("should change the cache within the send() call", () => {
|
|
292
|
+
const setup = createSetup("helpers");
|
|
293
|
+
mockRequest(setup.mutation, { data: { ok: true } });
|
|
294
|
+
|
|
295
|
+
const pending = setup.mutation.send();
|
|
296
|
+
|
|
297
|
+
expect(setup.read()).toStrictEqual(optimisticList("helpers"));
|
|
298
|
+
return pending;
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
it("should change the cache once an async callback resolves", async () => {
|
|
302
|
+
const setup = createSetup("helpers");
|
|
303
|
+
const request = setup.mutation.setOptimistic(async () => [optimistic(setup.list).insert(HELPER_ITEM)]);
|
|
304
|
+
mockRequest(request, { data: { ok: true }, delay: 20 });
|
|
305
|
+
|
|
306
|
+
const pending = request.send();
|
|
307
|
+
expect(setup.read()).toStrictEqual(INITIAL);
|
|
308
|
+
|
|
309
|
+
await waitFor(() => {
|
|
310
|
+
expect(setup.read()).toStrictEqual(optimisticList("helpers"));
|
|
311
|
+
});
|
|
312
|
+
await pending;
|
|
313
|
+
});
|
|
314
|
+
});
|
|
315
|
+
});
|