@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,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
|
+
});
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { waitFor } from "@testing-library/dom";
|
|
2
|
+
|
|
3
|
+
import { optimistic, resetOptimisticState } from "optimistic";
|
|
4
|
+
import type { Todo } from "../../utils/optimistic.utils";
|
|
5
|
+
import { createControlledClient, createTodo, readCache, seedCache } from "../../utils/optimistic.utils";
|
|
6
|
+
|
|
7
|
+
const BEFORE = [createTodo(1), createTodo(2)];
|
|
8
|
+
const OPTIMISTIC = [createTodo(1, { done: true }), createTodo(2)];
|
|
9
|
+
const AFTER = [createTodo(1, { done: true }), createTodo(2, { title: "changed on server" })];
|
|
10
|
+
|
|
11
|
+
const createSetup = (options: { seeded?: boolean } = {}) => {
|
|
12
|
+
const { client, calls, waitForCall } = createControlledClient();
|
|
13
|
+
const getTodos = client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos" });
|
|
14
|
+
const toggle = client
|
|
15
|
+
.createRequest<{ response: Todo; payload: Partial<Todo> }>()({ endpoint: "/todos/:todoId", method: "PATCH" })
|
|
16
|
+
.setParams({ todoId: 1 })
|
|
17
|
+
.setOptimistic(({ params, payload }) => [
|
|
18
|
+
optimistic(getTodos)
|
|
19
|
+
.patch(params.todoId, payload)
|
|
20
|
+
.rollback(({ data, previous }) => {
|
|
21
|
+
const before = previous.find((todo) => todo.id === params.todoId);
|
|
22
|
+
return data.map((todo) => (todo.id === params.todoId && before ? before : todo));
|
|
23
|
+
}),
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
if (options.seeded !== false) {
|
|
27
|
+
seedCache(client, getTodos, BEFORE);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const invalidate = vi.spyOn(client.cache, "invalidate");
|
|
31
|
+
const todos = () => readCache<Todo[]>(client, getTodos);
|
|
32
|
+
const callOf = (requestId: string) => calls.find((call) => call.requestId === requestId);
|
|
33
|
+
|
|
34
|
+
/** Starts a request and resolves to its id once it reaches the network */
|
|
35
|
+
const start = async (send: (onBeforeSent: (data: { requestId: string }) => void) => Promise<unknown>) => {
|
|
36
|
+
let requestId = "";
|
|
37
|
+
const promise = send(({ requestId: id }) => {
|
|
38
|
+
requestId = id;
|
|
39
|
+
});
|
|
40
|
+
await waitFor(
|
|
41
|
+
() => {
|
|
42
|
+
expect(callOf(requestId)).toBeDefined();
|
|
43
|
+
},
|
|
44
|
+
{ interval: 1 },
|
|
45
|
+
);
|
|
46
|
+
return { promise, call: callOf(requestId)! };
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const startFetch = () => start((onBeforeSent) => getTodos.send({ onBeforeSent }));
|
|
50
|
+
const startMutation = () => start((onBeforeSent) => toggle.send({ payload: { done: true }, onBeforeSent }));
|
|
51
|
+
|
|
52
|
+
return { client, calls, waitForCall, getTodos, toggle, invalidate, todos, startFetch, startMutation };
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
type Order = "fetch-first" | "mutation-first";
|
|
56
|
+
type Landing = "while-pending" | "after-settle";
|
|
57
|
+
type Outcome = "success" | "error";
|
|
58
|
+
|
|
59
|
+
const cases: { order: Order; landing: Landing; outcome: Outcome }[] = (
|
|
60
|
+
["fetch-first", "mutation-first"] as const
|
|
61
|
+
).flatMap((order) =>
|
|
62
|
+
(["while-pending", "after-settle"] as const).flatMap((landing) =>
|
|
63
|
+
(["success", "error"] as const).map((outcome) => ({ order, landing, outcome })),
|
|
64
|
+
),
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
describe("Optimistic [ Races with fetches ]", () => {
|
|
68
|
+
describe("when a fetch started before the mutation settled", () => {
|
|
69
|
+
it.each(cases)(
|
|
70
|
+
"should discard its response ($order, lands $landing, mutation $outcome)",
|
|
71
|
+
async ({ order, landing, outcome }) => {
|
|
72
|
+
const setup = createSetup();
|
|
73
|
+
|
|
74
|
+
const first = order === "fetch-first" ? await setup.startFetch() : await setup.startMutation();
|
|
75
|
+
const second = order === "fetch-first" ? await setup.startMutation() : await setup.startFetch();
|
|
76
|
+
const fetch = order === "fetch-first" ? first : second;
|
|
77
|
+
const mutation = order === "fetch-first" ? second : first;
|
|
78
|
+
|
|
79
|
+
expect(setup.todos()).toStrictEqual(OPTIMISTIC);
|
|
80
|
+
|
|
81
|
+
const settleMutation = async () => {
|
|
82
|
+
mutation.call.respond(outcome === "success" ? { data: OPTIMISTIC[0] } : { error: new Error("Failed") });
|
|
83
|
+
await mutation.promise;
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
if (landing === "after-settle") {
|
|
87
|
+
await settleMutation();
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// The server answers with what it had when the fetch was handled - before the change
|
|
91
|
+
fetch.call.respond({ data: BEFORE });
|
|
92
|
+
const fetchResponse = (await fetch.promise) as { data: Todo[] };
|
|
93
|
+
|
|
94
|
+
// The caller still receives its response, only the cache write is skipped
|
|
95
|
+
expect(fetchResponse.data).toStrictEqual(BEFORE);
|
|
96
|
+
expect(setup.todos()).toStrictEqual(landing === "after-settle" && outcome === "error" ? BEFORE : OPTIMISTIC);
|
|
97
|
+
|
|
98
|
+
if (landing === "while-pending") {
|
|
99
|
+
expect(setup.invalidate).not.toHaveBeenCalled();
|
|
100
|
+
await settleMutation();
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
expect(setup.todos()).toStrictEqual(outcome === "success" ? OPTIMISTIC : BEFORE);
|
|
104
|
+
// One refresh, once both the mutation and the stale fetch are done
|
|
105
|
+
expect(setup.invalidate).toHaveBeenCalledTimes(1);
|
|
106
|
+
expect(setup.invalidate).toHaveBeenCalledWith(setup.getTodos);
|
|
107
|
+
|
|
108
|
+
// The refresh fetch is written
|
|
109
|
+
const refresh = await setup.startFetch();
|
|
110
|
+
refresh.call.respond({ data: AFTER });
|
|
111
|
+
await refresh.promise;
|
|
112
|
+
expect(setup.todos()).toStrictEqual(AFTER);
|
|
113
|
+
},
|
|
114
|
+
);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
describe("when a fetch starts after the mutation settled", () => {
|
|
118
|
+
it.each(["success", "error"] as const)("should write its response (mutation %s)", async (outcome) => {
|
|
119
|
+
const setup = createSetup();
|
|
120
|
+
const mutation = await setup.startMutation();
|
|
121
|
+
mutation.call.respond(outcome === "success" ? { data: OPTIMISTIC[0] } : { error: new Error("Failed") });
|
|
122
|
+
await mutation.promise;
|
|
123
|
+
|
|
124
|
+
const fetch = await setup.startFetch();
|
|
125
|
+
fetch.call.respond({ data: AFTER });
|
|
126
|
+
await fetch.promise;
|
|
127
|
+
|
|
128
|
+
expect(setup.todos()).toStrictEqual(AFTER);
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
describe("when the stale fetch is still running at settle", () => {
|
|
133
|
+
it("should refresh only after the stale fetch is done", async () => {
|
|
134
|
+
const setup = createSetup();
|
|
135
|
+
const fetch = await setup.startFetch();
|
|
136
|
+
const mutation = await setup.startMutation();
|
|
137
|
+
|
|
138
|
+
mutation.call.respond({ data: OPTIMISTIC[0] });
|
|
139
|
+
await mutation.promise;
|
|
140
|
+
|
|
141
|
+
expect(setup.invalidate).not.toHaveBeenCalled();
|
|
142
|
+
|
|
143
|
+
fetch.call.respond({ data: BEFORE });
|
|
144
|
+
await fetch.promise;
|
|
145
|
+
|
|
146
|
+
expect(setup.invalidate).toHaveBeenCalledTimes(1);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it("should accept the retried attempt of a stale fetch", async () => {
|
|
150
|
+
const setup = createSetup();
|
|
151
|
+
const retried = setup.getTodos.setRetry(1).setRetryTime(0);
|
|
152
|
+
let requestId = "";
|
|
153
|
+
const promise = retried.send({
|
|
154
|
+
onBeforeSent: ({ requestId: id }) => {
|
|
155
|
+
requestId = id;
|
|
156
|
+
},
|
|
157
|
+
});
|
|
158
|
+
const firstAttempt = await setup.waitForCall(0);
|
|
159
|
+
const mutation = await setup.startMutation();
|
|
160
|
+
mutation.call.respond({ data: OPTIMISTIC[0] });
|
|
161
|
+
await mutation.promise;
|
|
162
|
+
|
|
163
|
+
// The attempt in flight at settle fails, the retry starts after the settle
|
|
164
|
+
firstAttempt.respond({ error: new Error("Network") });
|
|
165
|
+
const secondAttempt = await setup.waitForCall(2);
|
|
166
|
+
expect(secondAttempt.requestId).toBe(requestId);
|
|
167
|
+
secondAttempt.respond({ data: AFTER });
|
|
168
|
+
await promise;
|
|
169
|
+
|
|
170
|
+
expect(setup.todos()).toStrictEqual(AFTER);
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
describe("when the key has no data", () => {
|
|
175
|
+
it("should write the first load even while a mutation is pending", async () => {
|
|
176
|
+
const setup = createSetup({ seeded: false });
|
|
177
|
+
const mutation = await setup.startMutation();
|
|
178
|
+
const fetch = await setup.startFetch();
|
|
179
|
+
|
|
180
|
+
fetch.call.respond({ data: BEFORE });
|
|
181
|
+
await fetch.promise;
|
|
182
|
+
|
|
183
|
+
expect(setup.todos()).toStrictEqual(BEFORE);
|
|
184
|
+
|
|
185
|
+
mutation.call.respond({ data: OPTIMISTIC[0] });
|
|
186
|
+
await mutation.promise;
|
|
187
|
+
|
|
188
|
+
expect(setup.invalidate).toHaveBeenCalledWith(setup.getTodos);
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
describe("when the cache is written by hand", () => {
|
|
193
|
+
it("should never block manual writes while a mutation is pending", async () => {
|
|
194
|
+
const setup = createSetup();
|
|
195
|
+
const mutation = await setup.startMutation();
|
|
196
|
+
|
|
197
|
+
seedCache(setup.client, setup.getTodos, AFTER);
|
|
198
|
+
setup.client.cache.update(setup.getTodos, (prev) => ({ data: [...(prev?.data ?? []), createTodo(3)] }));
|
|
199
|
+
|
|
200
|
+
expect(setup.todos()).toStrictEqual([...AFTER, createTodo(3)]);
|
|
201
|
+
mutation.call.respond({ data: OPTIMISTIC[0] });
|
|
202
|
+
await mutation.promise;
|
|
203
|
+
});
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
describe("when other keys are fetched", () => {
|
|
207
|
+
it("should write responses of keys without pending mutations", async () => {
|
|
208
|
+
const setup = createSetup();
|
|
209
|
+
const getOther = setup.client.createRequest<{ response: Todo[] }>()({ endpoint: "/other" });
|
|
210
|
+
seedCache(setup.client, getOther, BEFORE);
|
|
211
|
+
const mutation = await setup.startMutation();
|
|
212
|
+
|
|
213
|
+
const promise = getOther.send();
|
|
214
|
+
const call = await setup.waitForCall(1);
|
|
215
|
+
call.respond({ data: AFTER });
|
|
216
|
+
await promise;
|
|
217
|
+
|
|
218
|
+
expect(readCache(setup.client, getOther)).toStrictEqual(AFTER);
|
|
219
|
+
mutation.call.respond({ data: OPTIMISTIC[0] });
|
|
220
|
+
await mutation.promise;
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
describe("when the client is cleared", () => {
|
|
225
|
+
it("should drop the pending state so later fetches are written", async () => {
|
|
226
|
+
const setup = createSetup();
|
|
227
|
+
await setup.startMutation();
|
|
228
|
+
|
|
229
|
+
setup.client.clear();
|
|
230
|
+
seedCache(setup.client, setup.getTodos, BEFORE);
|
|
231
|
+
const fetch = await setup.startFetch();
|
|
232
|
+
fetch.call.respond({ data: AFTER });
|
|
233
|
+
await fetch.promise;
|
|
234
|
+
|
|
235
|
+
expect(setup.todos()).toStrictEqual(AFTER);
|
|
236
|
+
});
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
describe("when the pending state is reset while a mutation is in flight", () => {
|
|
240
|
+
it("should still settle the mutation", async () => {
|
|
241
|
+
const setup = createSetup();
|
|
242
|
+
const mutation = await setup.startMutation();
|
|
243
|
+
|
|
244
|
+
resetOptimisticState(setup.client);
|
|
245
|
+
mutation.call.respond({ error: new Error("Failed") });
|
|
246
|
+
await mutation.promise;
|
|
247
|
+
|
|
248
|
+
expect(setup.todos()).toStrictEqual(BEFORE);
|
|
249
|
+
expect(setup.invalidate).not.toHaveBeenCalled();
|
|
250
|
+
});
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
describe("when a scope is used", () => {
|
|
254
|
+
it("should only guard the scope of the target", async () => {
|
|
255
|
+
const setup = createSetup();
|
|
256
|
+
const scoped = setup.getTodos.setScope("user-1");
|
|
257
|
+
seedCache(setup.client, scoped, BEFORE);
|
|
258
|
+
const mutation = await setup.startMutation();
|
|
259
|
+
|
|
260
|
+
const promise = scoped.send();
|
|
261
|
+
const call = await setup.waitForCall(1);
|
|
262
|
+
call.respond({ data: AFTER });
|
|
263
|
+
await promise;
|
|
264
|
+
|
|
265
|
+
expect(readCache(setup.client, scoped)).toStrictEqual(AFTER);
|
|
266
|
+
mutation.call.respond({ data: OPTIMISTIC[0] });
|
|
267
|
+
await mutation.promise;
|
|
268
|
+
});
|
|
269
|
+
});
|
|
270
|
+
});
|