@hyper-fetch/core 9.5.0 → 9.5.2
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/dispatcher/dispatcher.retry.spec.ts +220 -0
- package/__tests__/features/request/request.optimistic-settlement.spec.ts +1027 -0
- package/__tests__/features/request/request.response-mapper-failure.spec.ts +362 -0
- package/dist/dispatcher/dispatcher.d.ts +10 -0
- package/dist/dispatcher/dispatcher.d.ts.map +1 -1
- package/dist/index.mjs +180 -16
- package/dist/index.mjs.map +1 -1
- package/dist/request/request.d.ts +4 -4
- package/dist/request/request.types.d.ts +20 -3
- package/dist/request/request.types.d.ts.map +1 -1
- package/dist/request/request.utils.d.ts +12 -0
- package/dist/request/request.utils.d.ts.map +1 -1
- package/package.json +2 -3
- package/src/dispatcher/dispatcher.ts +49 -1
- package/src/request/request.ts +4 -4
- package/src/request/request.types.ts +15 -3
- package/src/request/request.utils.ts +158 -18
- package/release.config.js +0 -6
|
@@ -0,0 +1,1027 @@
|
|
|
1
|
+
import { createHttpMockingServer } from "@hyper-fetch/testing";
|
|
2
|
+
import { waitFor } from "@testing-library/dom";
|
|
3
|
+
import { getErrorMessage } from "adapter";
|
|
4
|
+
import { Client } from "client";
|
|
5
|
+
import type { RequestResponseEventType } from "managers";
|
|
6
|
+
import type { OptimisticRollbackArgs, RequestInstance } from "request";
|
|
7
|
+
import { scopeKey } from "request";
|
|
8
|
+
|
|
9
|
+
const { resetMocks, startServer, stopServer, mockRequest } = createHttpMockingServer();
|
|
10
|
+
|
|
11
|
+
const SERVER_ITEM = "server";
|
|
12
|
+
const OPTIMISTIC_ITEM = "optimistic";
|
|
13
|
+
const INITIAL_LIST = [SERVER_ITEM];
|
|
14
|
+
const OPTIMISTIC_LIST = [SERVER_ITEM, OPTIMISTIC_ITEM];
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Builds isolated client with a seeded list and a mutation which adds one item to it optimistically
|
|
18
|
+
*/
|
|
19
|
+
const createSetup = () => {
|
|
20
|
+
const client = new Client({ url: "shared-base-url" });
|
|
21
|
+
const list = client.createRequest<{ response: string[] }>()({ endpoint: "/list" });
|
|
22
|
+
|
|
23
|
+
client.cache.set(list, {
|
|
24
|
+
data: INITIAL_LIST,
|
|
25
|
+
error: null,
|
|
26
|
+
status: 200,
|
|
27
|
+
success: true,
|
|
28
|
+
extra: client.adapter.defaultExtra,
|
|
29
|
+
retries: 0,
|
|
30
|
+
isCanceled: false,
|
|
31
|
+
isOffline: false,
|
|
32
|
+
willRetry: false,
|
|
33
|
+
addedTimestamp: Date.now(),
|
|
34
|
+
triggerTimestamp: Date.now(),
|
|
35
|
+
requestTimestamp: Date.now(),
|
|
36
|
+
// Garbage collector drops the entries with outdated timestamps
|
|
37
|
+
responseTimestamp: Date.now(),
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const readList = () => client.cache.get<string[], unknown>(list.cacheKey)?.data;
|
|
41
|
+
const addItem = (item: string) => {
|
|
42
|
+
client.cache.update(list, (prev) => ({ data: [...(prev?.data ?? []), item] }));
|
|
43
|
+
};
|
|
44
|
+
const removeItem = (item: string) => {
|
|
45
|
+
client.cache.update(list, (prev) => ({ data: (prev?.data ?? []).filter((value) => value !== item) }));
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const rollback = vi.fn((_args: OptimisticRollbackArgs<any>) => {
|
|
49
|
+
removeItem(OPTIMISTIC_ITEM);
|
|
50
|
+
});
|
|
51
|
+
const invalidate = vi.spyOn(client.cache, "invalidate");
|
|
52
|
+
const logError = vi.spyOn(client.logger, "error");
|
|
53
|
+
|
|
54
|
+
const mutation = client
|
|
55
|
+
.createRequest<{ response: { ok: boolean } }>()({ endpoint: "/mutation", method: "POST" })
|
|
56
|
+
.setOptimistic(() => {
|
|
57
|
+
addItem(OPTIMISTIC_ITEM);
|
|
58
|
+
return { context: { item: OPTIMISTIC_ITEM }, rollback, invalidate: [list] };
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
const responses: RequestResponseEventType<RequestInstance>[] = [];
|
|
62
|
+
client.requestManager.events.onResponse((values) => {
|
|
63
|
+
responses.push(values);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
const dispatcher = client.submitDispatcher;
|
|
67
|
+
const queryKey = scopeKey(mutation.queryKey, mutation.scope);
|
|
68
|
+
const abortKey = scopeKey(mutation.abortKey, mutation.scope);
|
|
69
|
+
|
|
70
|
+
return {
|
|
71
|
+
client,
|
|
72
|
+
list,
|
|
73
|
+
mutation,
|
|
74
|
+
rollback,
|
|
75
|
+
invalidate,
|
|
76
|
+
logError,
|
|
77
|
+
responses,
|
|
78
|
+
dispatcher,
|
|
79
|
+
queryKey,
|
|
80
|
+
abortKey,
|
|
81
|
+
readList,
|
|
82
|
+
addItem,
|
|
83
|
+
removeItem,
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
type Setup = ReturnType<typeof createSetup>;
|
|
88
|
+
type Mutation = Setup["mutation"];
|
|
89
|
+
|
|
90
|
+
type Scenario = {
|
|
91
|
+
name: string;
|
|
92
|
+
build?: (setup: Setup) => Mutation;
|
|
93
|
+
/** Arrange the mocks and return options for the send call */
|
|
94
|
+
arrange: (setup: Setup, request: Mutation) => Record<string, unknown> | void;
|
|
95
|
+
/** Drive the request while it is pending */
|
|
96
|
+
drive?: (setup: Setup, request: Mutation) => Promise<void>;
|
|
97
|
+
/** Wait for the work trailing after the promise got resolved */
|
|
98
|
+
settled?: (setup: Setup) => Promise<void>;
|
|
99
|
+
expected: {
|
|
100
|
+
list: string[];
|
|
101
|
+
invalidated: boolean;
|
|
102
|
+
success: boolean;
|
|
103
|
+
rollback?: {
|
|
104
|
+
reason: "error" | "abort" | "removed";
|
|
105
|
+
status?: number;
|
|
106
|
+
errorMessage?: string;
|
|
107
|
+
};
|
|
108
|
+
resultError?: string;
|
|
109
|
+
};
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const waitForResponses = async (setup: Setup, count: number) => {
|
|
113
|
+
await waitFor(() => {
|
|
114
|
+
expect(setup.responses).toHaveLength(count);
|
|
115
|
+
});
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const goOfflineOnFirstAttempt = (setup: Setup) => {
|
|
119
|
+
let isFirstAttempt = true;
|
|
120
|
+
return {
|
|
121
|
+
onRequestStart: () => {
|
|
122
|
+
if (isFirstAttempt) {
|
|
123
|
+
isFirstAttempt = false;
|
|
124
|
+
setup.client.appManager.setOnline(false);
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const scenarios: Scenario[] = [
|
|
131
|
+
{
|
|
132
|
+
name: "success",
|
|
133
|
+
arrange: (_, request) => {
|
|
134
|
+
mockRequest(request, { data: { ok: true } });
|
|
135
|
+
},
|
|
136
|
+
expected: { list: OPTIMISTIC_LIST, invalidated: true, success: true },
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
name: "final error",
|
|
140
|
+
arrange: (_, request) => {
|
|
141
|
+
mockRequest(request, { status: 400 });
|
|
142
|
+
},
|
|
143
|
+
expected: {
|
|
144
|
+
list: INITIAL_LIST,
|
|
145
|
+
invalidated: false,
|
|
146
|
+
success: false,
|
|
147
|
+
rollback: { reason: "error", status: 400 },
|
|
148
|
+
},
|
|
149
|
+
},
|
|
150
|
+
{
|
|
151
|
+
name: "abort",
|
|
152
|
+
arrange: (_, request) => {
|
|
153
|
+
mockRequest(request, { delay: 100 });
|
|
154
|
+
return {
|
|
155
|
+
onRequestStart: () => {
|
|
156
|
+
request.abort();
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
},
|
|
160
|
+
expected: {
|
|
161
|
+
list: INITIAL_LIST,
|
|
162
|
+
invalidated: false,
|
|
163
|
+
success: false,
|
|
164
|
+
rollback: { reason: "abort", errorMessage: getErrorMessage("abort").message },
|
|
165
|
+
resultError: getErrorMessage("abort").message,
|
|
166
|
+
},
|
|
167
|
+
},
|
|
168
|
+
{
|
|
169
|
+
name: "removal of a queued request",
|
|
170
|
+
arrange: (setup, request) => {
|
|
171
|
+
mockRequest(request);
|
|
172
|
+
setup.dispatcher.stop(setup.queryKey);
|
|
173
|
+
return {
|
|
174
|
+
onBeforeSent: ({ requestId }: { requestId: string }) => {
|
|
175
|
+
// Listeners of the send call are attached right after this callback
|
|
176
|
+
queueMicrotask(() => {
|
|
177
|
+
setup.dispatcher.delete(setup.queryKey, requestId, setup.abortKey);
|
|
178
|
+
});
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
},
|
|
182
|
+
expected: {
|
|
183
|
+
list: INITIAL_LIST,
|
|
184
|
+
invalidated: false,
|
|
185
|
+
success: false,
|
|
186
|
+
rollback: { reason: "removed" },
|
|
187
|
+
resultError: getErrorMessage("deleted").message,
|
|
188
|
+
},
|
|
189
|
+
},
|
|
190
|
+
{
|
|
191
|
+
name: "removal of a running request",
|
|
192
|
+
arrange: (setup, request) => {
|
|
193
|
+
mockRequest(request, { delay: 100 });
|
|
194
|
+
return {
|
|
195
|
+
onRequestStart: ({ requestId }: { requestId: string }) => {
|
|
196
|
+
setup.dispatcher.delete(setup.queryKey, requestId, setup.abortKey);
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
},
|
|
200
|
+
// The aborted adapter responds after the promise was already resolved
|
|
201
|
+
settled: (setup) => waitForResponses(setup, 1),
|
|
202
|
+
expected: {
|
|
203
|
+
list: INITIAL_LIST,
|
|
204
|
+
invalidated: false,
|
|
205
|
+
success: false,
|
|
206
|
+
rollback: { reason: "removed" },
|
|
207
|
+
resultError: getErrorMessage("deleted").message,
|
|
208
|
+
},
|
|
209
|
+
},
|
|
210
|
+
{
|
|
211
|
+
name: "retry then success",
|
|
212
|
+
build: ({ mutation }) => mutation.setRetry(1).setRetryTime(10),
|
|
213
|
+
arrange: (setup, request) => {
|
|
214
|
+
mockRequest(request, { status: 400 });
|
|
215
|
+
const unmount = setup.client.requestManager.events.onResponse(() => {
|
|
216
|
+
unmount();
|
|
217
|
+
mockRequest(request, { data: { ok: true } });
|
|
218
|
+
});
|
|
219
|
+
},
|
|
220
|
+
expected: { list: OPTIMISTIC_LIST, invalidated: true, success: true },
|
|
221
|
+
},
|
|
222
|
+
{
|
|
223
|
+
name: "retry then error",
|
|
224
|
+
build: ({ mutation }) => mutation.setRetry(1).setRetryTime(10),
|
|
225
|
+
arrange: (setup, request) => {
|
|
226
|
+
mockRequest(request, { status: 400 });
|
|
227
|
+
const unmount = setup.client.requestManager.events.onResponse(() => {
|
|
228
|
+
unmount();
|
|
229
|
+
mockRequest(request, { status: 500 });
|
|
230
|
+
});
|
|
231
|
+
},
|
|
232
|
+
expected: {
|
|
233
|
+
list: INITIAL_LIST,
|
|
234
|
+
invalidated: false,
|
|
235
|
+
success: false,
|
|
236
|
+
rollback: { reason: "error", status: 500 },
|
|
237
|
+
},
|
|
238
|
+
},
|
|
239
|
+
{
|
|
240
|
+
name: "offline then success",
|
|
241
|
+
arrange: (setup, request) => {
|
|
242
|
+
mockRequest(request, { status: 400, delay: 30 });
|
|
243
|
+
return goOfflineOnFirstAttempt(setup);
|
|
244
|
+
},
|
|
245
|
+
drive: async (setup, request) => {
|
|
246
|
+
await waitForResponses(setup, 1);
|
|
247
|
+
expect(setup.rollback).not.toHaveBeenCalled();
|
|
248
|
+
expect(setup.readList()).toStrictEqual(OPTIMISTIC_LIST);
|
|
249
|
+
mockRequest(request, { data: { ok: true } });
|
|
250
|
+
setup.client.appManager.setOnline(true);
|
|
251
|
+
},
|
|
252
|
+
expected: { list: OPTIMISTIC_LIST, invalidated: true, success: true },
|
|
253
|
+
},
|
|
254
|
+
{
|
|
255
|
+
name: "offline then error",
|
|
256
|
+
arrange: (setup, request) => {
|
|
257
|
+
mockRequest(request, { status: 400, delay: 30 });
|
|
258
|
+
return goOfflineOnFirstAttempt(setup);
|
|
259
|
+
},
|
|
260
|
+
drive: async (setup, request) => {
|
|
261
|
+
await waitForResponses(setup, 1);
|
|
262
|
+
expect(setup.rollback).not.toHaveBeenCalled();
|
|
263
|
+
expect(setup.readList()).toStrictEqual(OPTIMISTIC_LIST);
|
|
264
|
+
mockRequest(request, { status: 500 });
|
|
265
|
+
setup.client.appManager.setOnline(true);
|
|
266
|
+
},
|
|
267
|
+
expected: {
|
|
268
|
+
list: INITIAL_LIST,
|
|
269
|
+
invalidated: false,
|
|
270
|
+
success: false,
|
|
271
|
+
rollback: { reason: "error", status: 500 },
|
|
272
|
+
},
|
|
273
|
+
},
|
|
274
|
+
];
|
|
275
|
+
|
|
276
|
+
const entryPoints = [
|
|
277
|
+
{
|
|
278
|
+
name: "send()",
|
|
279
|
+
run: (request: Mutation, options: Record<string, unknown>) => {
|
|
280
|
+
return request.send(options as any).then((result) => ({ result, observed: null }));
|
|
281
|
+
},
|
|
282
|
+
},
|
|
283
|
+
{
|
|
284
|
+
name: "$hooks",
|
|
285
|
+
run: (request: Mutation, options: Record<string, unknown>, setup?: Setup) => {
|
|
286
|
+
let observed: { list?: string[] | null; rollbacks: number; invalidations: number } | null = null;
|
|
287
|
+
const observe = () => {
|
|
288
|
+
observed = {
|
|
289
|
+
list: setup?.readList(),
|
|
290
|
+
rollbacks: setup?.rollback.mock.calls.length ?? 0,
|
|
291
|
+
invalidations: setup?.invalidate.mock.calls.length ?? 0,
|
|
292
|
+
};
|
|
293
|
+
};
|
|
294
|
+
request.$hooks.onResponse(observe);
|
|
295
|
+
request.$hooks.onRemove(observe);
|
|
296
|
+
return request.send(options as any).then((result) => ({ result, observed }));
|
|
297
|
+
},
|
|
298
|
+
},
|
|
299
|
+
];
|
|
300
|
+
|
|
301
|
+
describe("Request [ Optimistic settlement ]", () => {
|
|
302
|
+
beforeAll(() => {
|
|
303
|
+
startServer();
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
afterEach(() => {
|
|
307
|
+
resetMocks();
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
afterAll(() => {
|
|
311
|
+
stopServer();
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
describe.each(entryPoints)("when using $name", ({ name: entryPoint, run }) => {
|
|
315
|
+
it.each(scenarios)("should settle $name", async ({ build, arrange, drive, settled, expected }) => {
|
|
316
|
+
const setup = createSetup();
|
|
317
|
+
const request = build?.(setup) ?? setup.mutation;
|
|
318
|
+
let sentRequest: RequestInstance | undefined;
|
|
319
|
+
|
|
320
|
+
const options = arrange(setup, request) ?? {};
|
|
321
|
+
const pending = run(
|
|
322
|
+
request,
|
|
323
|
+
{
|
|
324
|
+
...options,
|
|
325
|
+
onBeforeSent: (data: { request: RequestInstance; requestId: string }) => {
|
|
326
|
+
sentRequest = data.request;
|
|
327
|
+
(options as { onBeforeSent?: (value: typeof data) => void }).onBeforeSent?.(data);
|
|
328
|
+
},
|
|
329
|
+
},
|
|
330
|
+
setup,
|
|
331
|
+
);
|
|
332
|
+
|
|
333
|
+
await drive?.(setup, request);
|
|
334
|
+
const { result, observed } = await pending;
|
|
335
|
+
await settled?.(setup);
|
|
336
|
+
|
|
337
|
+
expect(setup.readList()).toStrictEqual(expected.list);
|
|
338
|
+
expect(result.success).toBe(expected.success);
|
|
339
|
+
if (expected.resultError) {
|
|
340
|
+
expect((result.error as Error).message).toBe(expected.resultError);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
if (expected.invalidated) {
|
|
344
|
+
expect(setup.invalidate).toHaveBeenCalledTimes(1);
|
|
345
|
+
expect(setup.invalidate).toHaveBeenCalledWith(setup.list);
|
|
346
|
+
expect(setup.client.cache.get(setup.list.cacheKey)?.staleTime).toBe(0);
|
|
347
|
+
} else {
|
|
348
|
+
expect(setup.invalidate).not.toHaveBeenCalled();
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
if (expected.rollback) {
|
|
352
|
+
expect(setup.rollback).toHaveBeenCalledTimes(1);
|
|
353
|
+
const [args] = setup.rollback.mock.calls[0];
|
|
354
|
+
expect(args.reason).toBe(expected.rollback.reason);
|
|
355
|
+
expect(args.request).toBe(sentRequest);
|
|
356
|
+
|
|
357
|
+
if (expected.rollback.reason === "removed") {
|
|
358
|
+
expect(args.response).toBeUndefined();
|
|
359
|
+
expect(args).not.toHaveProperty("response");
|
|
360
|
+
} else {
|
|
361
|
+
expect(args.response?.success).toBe(false);
|
|
362
|
+
}
|
|
363
|
+
if (expected.rollback.status) {
|
|
364
|
+
expect(args.response?.status).toBe(expected.rollback.status);
|
|
365
|
+
}
|
|
366
|
+
if (expected.rollback.errorMessage) {
|
|
367
|
+
expect(args.response?.error).toHaveProperty("message", expected.rollback.errorMessage);
|
|
368
|
+
}
|
|
369
|
+
} else {
|
|
370
|
+
expect(setup.rollback).not.toHaveBeenCalled();
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// Lifecycle listeners have to see the state that is already settled
|
|
374
|
+
if (entryPoint === "$hooks") {
|
|
375
|
+
expect(observed).toStrictEqual({
|
|
376
|
+
list: expected.list,
|
|
377
|
+
rollbacks: expected.rollback ? 1 : 0,
|
|
378
|
+
invalidations: expected.invalidated ? 1 : 0,
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
});
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
describe("when the request never gets sent", () => {
|
|
385
|
+
it("should not roll back when optimistic callback throws", async () => {
|
|
386
|
+
const { client } = createSetup();
|
|
387
|
+
const rollback = vi.fn();
|
|
388
|
+
const add = vi.spyOn(client.submitDispatcher, "add");
|
|
389
|
+
const request = client
|
|
390
|
+
.createRequest<{ response: null }>()({ endpoint: "/mutation", method: "POST" })
|
|
391
|
+
.setOptimistic(() => {
|
|
392
|
+
throw new Error("Optimistic failed");
|
|
393
|
+
// eslint-disable-next-line no-unreachable
|
|
394
|
+
return { rollback };
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
const result = await request.send();
|
|
398
|
+
|
|
399
|
+
expect(result.success).toBe(false);
|
|
400
|
+
expect(add).not.toHaveBeenCalled();
|
|
401
|
+
expect(rollback).not.toHaveBeenCalled();
|
|
402
|
+
});
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
describe("when optimistic callback returns partial result", () => {
|
|
406
|
+
it("should resolve failed request without rollback", async () => {
|
|
407
|
+
const { client } = createSetup();
|
|
408
|
+
const request = client
|
|
409
|
+
.createRequest<{ response: null }>()({ endpoint: "/mutation", method: "POST" })
|
|
410
|
+
.setOptimistic(() => ({}));
|
|
411
|
+
mockRequest(request, { status: 400 });
|
|
412
|
+
|
|
413
|
+
const result = await request.send();
|
|
414
|
+
|
|
415
|
+
expect(result.status).toBe(400);
|
|
416
|
+
});
|
|
417
|
+
|
|
418
|
+
it("should resolve successful request without invalidate", async () => {
|
|
419
|
+
const { client, invalidate } = createSetup();
|
|
420
|
+
const request = client
|
|
421
|
+
.createRequest<{ response: null }>()({ endpoint: "/mutation", method: "POST" })
|
|
422
|
+
.setOptimistic(() => ({}));
|
|
423
|
+
mockRequest(request);
|
|
424
|
+
|
|
425
|
+
const result = await request.send();
|
|
426
|
+
|
|
427
|
+
expect(result.success).toBeTrue();
|
|
428
|
+
expect(invalidate).not.toHaveBeenCalled();
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
it("should support rollback declared without arguments", async () => {
|
|
432
|
+
const { client } = createSetup();
|
|
433
|
+
let calls = 0;
|
|
434
|
+
const request = client
|
|
435
|
+
.createRequest<{ response: null }>()({ endpoint: "/mutation", method: "POST" })
|
|
436
|
+
.setOptimistic(() => ({
|
|
437
|
+
rollback: () => {
|
|
438
|
+
calls += 1;
|
|
439
|
+
},
|
|
440
|
+
}));
|
|
441
|
+
mockRequest(request, { status: 400 });
|
|
442
|
+
|
|
443
|
+
await request.send();
|
|
444
|
+
|
|
445
|
+
expect(calls).toBe(1);
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
it("should use rollback returned from async optimistic callback", async () => {
|
|
449
|
+
const { client } = createSetup();
|
|
450
|
+
const rollback = vi.fn();
|
|
451
|
+
const request = client
|
|
452
|
+
.createRequest<{ response: null }>()({ endpoint: "/mutation", method: "POST" })
|
|
453
|
+
.setOptimistic(async () => ({ rollback }));
|
|
454
|
+
mockRequest(request, { status: 400 });
|
|
455
|
+
|
|
456
|
+
await request.send();
|
|
457
|
+
|
|
458
|
+
expect(rollback).toHaveBeenCalledTimes(1);
|
|
459
|
+
expect(rollback.mock.calls[0][0]).toHaveProperty("reason", "error");
|
|
460
|
+
});
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
describe("when settlement callbacks fail", () => {
|
|
464
|
+
it("should resolve normally and log when rollback throws", async () => {
|
|
465
|
+
const { client, logError } = createSetup();
|
|
466
|
+
const failure = new Error("Rollback failed");
|
|
467
|
+
const request = client
|
|
468
|
+
.createRequest<{ response: null }>()({ endpoint: "/mutation", method: "POST" })
|
|
469
|
+
.setOptimistic(() => ({
|
|
470
|
+
rollback: () => {
|
|
471
|
+
throw failure;
|
|
472
|
+
},
|
|
473
|
+
}));
|
|
474
|
+
mockRequest(request, { status: 400 });
|
|
475
|
+
|
|
476
|
+
const result = await request.send();
|
|
477
|
+
|
|
478
|
+
expect(result.status).toBe(400);
|
|
479
|
+
expect(logError).toHaveBeenCalledTimes(1);
|
|
480
|
+
expect(logError.mock.calls[0][0].extra).toMatchObject({ error: failure, reason: "error" });
|
|
481
|
+
});
|
|
482
|
+
|
|
483
|
+
it("should resolve normally and log when async rollback rejects", async () => {
|
|
484
|
+
const { client, logError } = createSetup();
|
|
485
|
+
const failure = new Error("Async rollback failed");
|
|
486
|
+
const request = client
|
|
487
|
+
.createRequest<{ response: null }>()({ endpoint: "/mutation", method: "POST" })
|
|
488
|
+
.setOptimistic(() => ({
|
|
489
|
+
rollback: async () => {
|
|
490
|
+
throw failure;
|
|
491
|
+
},
|
|
492
|
+
}));
|
|
493
|
+
mockRequest(request, { status: 400 });
|
|
494
|
+
|
|
495
|
+
const result = await request.send();
|
|
496
|
+
|
|
497
|
+
expect(result.status).toBe(400);
|
|
498
|
+
await waitFor(() => {
|
|
499
|
+
expect(logError).toHaveBeenCalledTimes(1);
|
|
500
|
+
});
|
|
501
|
+
expect(logError.mock.calls[0][0].extra).toMatchObject({ error: failure, reason: "error" });
|
|
502
|
+
});
|
|
503
|
+
|
|
504
|
+
it("should resolve normally and log when rollback throws during queue removal", async () => {
|
|
505
|
+
const { client, logError } = createSetup();
|
|
506
|
+
const request = client
|
|
507
|
+
.createRequest<{ response: null }>()({ endpoint: "/mutation", method: "POST" })
|
|
508
|
+
.setOptimistic(() => ({
|
|
509
|
+
rollback: () => {
|
|
510
|
+
throw new Error("Rollback failed");
|
|
511
|
+
},
|
|
512
|
+
}));
|
|
513
|
+
const queryKey = scopeKey(request.queryKey, request.scope);
|
|
514
|
+
client.submitDispatcher.stop(queryKey);
|
|
515
|
+
|
|
516
|
+
const result = await request.send({
|
|
517
|
+
onBeforeSent: ({ requestId }) => {
|
|
518
|
+
queueMicrotask(() => {
|
|
519
|
+
client.submitDispatcher.delete(queryKey, requestId, scopeKey(request.abortKey, request.scope));
|
|
520
|
+
});
|
|
521
|
+
},
|
|
522
|
+
});
|
|
523
|
+
|
|
524
|
+
expect((result.error as Error).message).toBe(getErrorMessage("deleted").message);
|
|
525
|
+
expect(logError).toHaveBeenCalledTimes(1);
|
|
526
|
+
});
|
|
527
|
+
|
|
528
|
+
it("should keep invalidating other targets and log when invalidation throws", async () => {
|
|
529
|
+
const { client, invalidate, logError, list } = createSetup();
|
|
530
|
+
const failure = new Error("Invalidate failed");
|
|
531
|
+
const other = client.createRequest<{ response: null }>()({ endpoint: "/other" });
|
|
532
|
+
invalidate.mockImplementationOnce(() => {
|
|
533
|
+
throw failure;
|
|
534
|
+
});
|
|
535
|
+
const request = client
|
|
536
|
+
.createRequest<{ response: null }>()({ endpoint: "/mutation", method: "POST" })
|
|
537
|
+
.setOptimistic(() => ({ invalidate: [list, other] }));
|
|
538
|
+
mockRequest(request);
|
|
539
|
+
|
|
540
|
+
const result = await request.send();
|
|
541
|
+
|
|
542
|
+
expect(result.success).toBeTrue();
|
|
543
|
+
expect(invalidate).toHaveBeenCalledTimes(2);
|
|
544
|
+
expect(invalidate).toHaveBeenLastCalledWith(other);
|
|
545
|
+
expect(logError).toHaveBeenCalledTimes(1);
|
|
546
|
+
expect(logError.mock.calls[0][0].extra).toMatchObject({ error: failure, target: list });
|
|
547
|
+
});
|
|
548
|
+
});
|
|
549
|
+
|
|
550
|
+
describe("when observing the order of events", () => {
|
|
551
|
+
it("should roll back before response listeners attached in onBeforeSent", async () => {
|
|
552
|
+
const { client, mutation, rollback } = createSetup();
|
|
553
|
+
const order: string[] = [];
|
|
554
|
+
rollback.mockImplementation(() => {
|
|
555
|
+
order.push("rollback");
|
|
556
|
+
});
|
|
557
|
+
mockRequest(mutation, { status: 400 });
|
|
558
|
+
|
|
559
|
+
await mutation.send({
|
|
560
|
+
onBeforeSent: ({ requestId }) => {
|
|
561
|
+
client.requestManager.events.onResponseById(requestId, () => {
|
|
562
|
+
order.push("listener");
|
|
563
|
+
});
|
|
564
|
+
},
|
|
565
|
+
onResponse: () => {
|
|
566
|
+
order.push("onResponse");
|
|
567
|
+
},
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
expect(order).toStrictEqual(["rollback", "listener", "onResponse"]);
|
|
571
|
+
});
|
|
572
|
+
|
|
573
|
+
it("should invalidate before response listeners attached in onBeforeSent", async () => {
|
|
574
|
+
const { client, mutation, invalidate } = createSetup();
|
|
575
|
+
const order: string[] = [];
|
|
576
|
+
invalidate.mockImplementation(() => {
|
|
577
|
+
order.push("invalidate");
|
|
578
|
+
});
|
|
579
|
+
mockRequest(mutation);
|
|
580
|
+
|
|
581
|
+
await mutation.send({
|
|
582
|
+
onBeforeSent: ({ requestId }) => {
|
|
583
|
+
client.requestManager.events.onResponseById(requestId, () => {
|
|
584
|
+
order.push("listener");
|
|
585
|
+
});
|
|
586
|
+
},
|
|
587
|
+
onResponse: () => {
|
|
588
|
+
order.push("onResponse");
|
|
589
|
+
},
|
|
590
|
+
});
|
|
591
|
+
|
|
592
|
+
expect(order).toStrictEqual(["invalidate", "listener", "onResponse"]);
|
|
593
|
+
});
|
|
594
|
+
|
|
595
|
+
it("should roll back before removal callbacks", async () => {
|
|
596
|
+
const { mutation, rollback, dispatcher, queryKey, abortKey } = createSetup();
|
|
597
|
+
const order: string[] = [];
|
|
598
|
+
rollback.mockImplementation(() => {
|
|
599
|
+
order.push("rollback");
|
|
600
|
+
});
|
|
601
|
+
dispatcher.stop(queryKey);
|
|
602
|
+
|
|
603
|
+
await mutation.send({
|
|
604
|
+
onBeforeSent: ({ requestId }) => {
|
|
605
|
+
queueMicrotask(() => {
|
|
606
|
+
dispatcher.delete(queryKey, requestId, abortKey);
|
|
607
|
+
});
|
|
608
|
+
},
|
|
609
|
+
onRemove: () => {
|
|
610
|
+
order.push("onRemove");
|
|
611
|
+
},
|
|
612
|
+
});
|
|
613
|
+
|
|
614
|
+
expect(order).toStrictEqual(["rollback", "onRemove"]);
|
|
615
|
+
});
|
|
616
|
+
});
|
|
617
|
+
|
|
618
|
+
describe("when response is mapped", () => {
|
|
619
|
+
it("should pass the mapped response to rollback", async () => {
|
|
620
|
+
const { mutation, rollback } = createSetup();
|
|
621
|
+
const request = mutation.setResponseMapper((response) => ({ ...response, status: 418 }) as typeof response);
|
|
622
|
+
mockRequest(request, { status: 400 });
|
|
623
|
+
|
|
624
|
+
await request.send();
|
|
625
|
+
|
|
626
|
+
expect(rollback).toHaveBeenCalledTimes(1);
|
|
627
|
+
expect(rollback.mock.calls[0][0].response?.status).toBe(418);
|
|
628
|
+
});
|
|
629
|
+
|
|
630
|
+
it("should run the mapper once per response", async () => {
|
|
631
|
+
const { mutation } = createSetup();
|
|
632
|
+
const mapper = vi.fn((response) => response);
|
|
633
|
+
const request = mutation.setResponseMapper(mapper);
|
|
634
|
+
mockRequest(request, { status: 400 });
|
|
635
|
+
|
|
636
|
+
await request.send();
|
|
637
|
+
|
|
638
|
+
expect(mapper).toHaveBeenCalledTimes(1);
|
|
639
|
+
});
|
|
640
|
+
|
|
641
|
+
it("should run the async mapper once per response", async () => {
|
|
642
|
+
const { mutation } = createSetup();
|
|
643
|
+
const mapper = vi.fn(async (response) => response);
|
|
644
|
+
const request = mutation.setResponseMapper(mapper);
|
|
645
|
+
mockRequest(request, { status: 400 });
|
|
646
|
+
|
|
647
|
+
await request.send();
|
|
648
|
+
|
|
649
|
+
expect(mapper).toHaveBeenCalledTimes(1);
|
|
650
|
+
});
|
|
651
|
+
|
|
652
|
+
it("should roll back when mapper turns success into failure", async () => {
|
|
653
|
+
const { mutation, rollback, invalidate, readList } = createSetup();
|
|
654
|
+
const request = mutation.setResponseMapper(
|
|
655
|
+
(response) => ({ ...response, success: false, status: 422 }) as typeof response,
|
|
656
|
+
);
|
|
657
|
+
mockRequest(request);
|
|
658
|
+
|
|
659
|
+
await request.send();
|
|
660
|
+
|
|
661
|
+
expect(rollback).toHaveBeenCalledTimes(1);
|
|
662
|
+
expect(rollback.mock.calls[0][0]).toMatchObject({ reason: "error" });
|
|
663
|
+
expect(rollback.mock.calls[0][0].response?.status).toBe(422);
|
|
664
|
+
expect(invalidate).not.toHaveBeenCalled();
|
|
665
|
+
expect(readList()).toStrictEqual(INITIAL_LIST);
|
|
666
|
+
});
|
|
667
|
+
|
|
668
|
+
it("should invalidate when mapper turns failure into success", async () => {
|
|
669
|
+
const { mutation, rollback, invalidate, list } = createSetup();
|
|
670
|
+
const request = mutation.setResponseMapper(
|
|
671
|
+
(response) => ({ ...response, success: true, error: null }) as typeof response,
|
|
672
|
+
);
|
|
673
|
+
mockRequest(request, { status: 400 });
|
|
674
|
+
|
|
675
|
+
await request.send();
|
|
676
|
+
|
|
677
|
+
expect(rollback).not.toHaveBeenCalled();
|
|
678
|
+
expect(invalidate).toHaveBeenCalledTimes(1);
|
|
679
|
+
expect(invalidate).toHaveBeenCalledWith(list);
|
|
680
|
+
});
|
|
681
|
+
|
|
682
|
+
it("should report final error once when async mapper outlives queue removal", async () => {
|
|
683
|
+
const { mutation, rollback, dispatcher, queryKey } = createSetup();
|
|
684
|
+
let release: VoidFunction = () => undefined;
|
|
685
|
+
const gate = new Promise<void>((resolve) => {
|
|
686
|
+
release = resolve;
|
|
687
|
+
});
|
|
688
|
+
const request = mutation.setResponseMapper(async (response) => {
|
|
689
|
+
await gate;
|
|
690
|
+
return { ...response, status: 418 } as typeof response;
|
|
691
|
+
});
|
|
692
|
+
mockRequest(request, { status: 400 });
|
|
693
|
+
|
|
694
|
+
const pending = request.send();
|
|
695
|
+
// The dispatcher drops finished request from the queue before the mapper is done
|
|
696
|
+
await waitFor(() => {
|
|
697
|
+
expect(dispatcher.getQueue(queryKey).requests).toHaveLength(0);
|
|
698
|
+
});
|
|
699
|
+
expect(rollback).not.toHaveBeenCalled();
|
|
700
|
+
release();
|
|
701
|
+
const result = await pending;
|
|
702
|
+
|
|
703
|
+
expect(result.status).toBe(418);
|
|
704
|
+
expect(rollback).toHaveBeenCalledTimes(1);
|
|
705
|
+
expect(rollback.mock.calls[0][0]).toMatchObject({ reason: "error" });
|
|
706
|
+
expect(rollback.mock.calls[0][0].response?.status).toBe(418);
|
|
707
|
+
});
|
|
708
|
+
|
|
709
|
+
it("should ignore mapped response resolved after the request got removed", async () => {
|
|
710
|
+
const { mutation, rollback, invalidate, dispatcher, queryKey, abortKey, responses } = createSetup();
|
|
711
|
+
// The retry timer is not part of this case
|
|
712
|
+
vi.spyOn(dispatcher, "performRequest");
|
|
713
|
+
let release: VoidFunction = () => undefined;
|
|
714
|
+
const gate = new Promise<void>((resolve) => {
|
|
715
|
+
release = resolve;
|
|
716
|
+
});
|
|
717
|
+
const mapper = vi.fn(async (response) => {
|
|
718
|
+
await gate;
|
|
719
|
+
return { ...response, success: true, error: null };
|
|
720
|
+
});
|
|
721
|
+
const request = mutation.setRetry(1).setRetryTime(50).setResponseMapper(mapper);
|
|
722
|
+
mockRequest(request, { status: 400 });
|
|
723
|
+
const onResponse = vi.fn();
|
|
724
|
+
let requestId = "";
|
|
725
|
+
|
|
726
|
+
const pending = request.send({
|
|
727
|
+
onBeforeSent: (data) => {
|
|
728
|
+
requestId = data.requestId;
|
|
729
|
+
},
|
|
730
|
+
onResponse,
|
|
731
|
+
});
|
|
732
|
+
await waitFor(() => {
|
|
733
|
+
expect(responses).toHaveLength(1);
|
|
734
|
+
});
|
|
735
|
+
vi.mocked(dispatcher.performRequest).mockImplementation(async () => undefined);
|
|
736
|
+
|
|
737
|
+
dispatcher.delete(queryKey, requestId, abortKey);
|
|
738
|
+
const result = await pending;
|
|
739
|
+
release();
|
|
740
|
+
await mapper.mock.results[0].value;
|
|
741
|
+
|
|
742
|
+
expect((result.error as Error).message).toBe(getErrorMessage("deleted").message);
|
|
743
|
+
expect(rollback).toHaveBeenCalledTimes(1);
|
|
744
|
+
expect(rollback.mock.calls[0][0]).toMatchObject({ reason: "removed" });
|
|
745
|
+
expect(invalidate).not.toHaveBeenCalled();
|
|
746
|
+
expect(onResponse).not.toHaveBeenCalled();
|
|
747
|
+
});
|
|
748
|
+
|
|
749
|
+
it("should roll back aborted request with async mapper", async () => {
|
|
750
|
+
const { mutation, rollback } = createSetup();
|
|
751
|
+
const request = mutation.setResponseMapper(async (response) => response);
|
|
752
|
+
mockRequest(request, { delay: 100 });
|
|
753
|
+
|
|
754
|
+
await request.send({
|
|
755
|
+
onRequestStart: () => {
|
|
756
|
+
request.abort();
|
|
757
|
+
},
|
|
758
|
+
});
|
|
759
|
+
|
|
760
|
+
expect(rollback).toHaveBeenCalledTimes(1);
|
|
761
|
+
expect(rollback.mock.calls[0][0]).toMatchObject({ reason: "abort" });
|
|
762
|
+
});
|
|
763
|
+
});
|
|
764
|
+
|
|
765
|
+
describe("when request is postponed", () => {
|
|
766
|
+
it("should roll back and resolve when removed while waiting for a retry", async () => {
|
|
767
|
+
const { mutation, rollback, dispatcher, queryKey, abortKey, responses, readList } = createSetup();
|
|
768
|
+
// The retry timer is not part of this case
|
|
769
|
+
vi.spyOn(dispatcher, "performRequest");
|
|
770
|
+
const request = mutation.setRetry(1).setRetryTime(50);
|
|
771
|
+
mockRequest(request, { status: 400 });
|
|
772
|
+
let requestId = "";
|
|
773
|
+
|
|
774
|
+
const pending = request.send({
|
|
775
|
+
onBeforeSent: (data) => {
|
|
776
|
+
requestId = data.requestId;
|
|
777
|
+
},
|
|
778
|
+
});
|
|
779
|
+
await waitFor(() => {
|
|
780
|
+
expect(responses).toHaveLength(1);
|
|
781
|
+
});
|
|
782
|
+
vi.mocked(dispatcher.performRequest).mockImplementation(async () => undefined);
|
|
783
|
+
expect(rollback).not.toHaveBeenCalled();
|
|
784
|
+
|
|
785
|
+
dispatcher.delete(queryKey, requestId, abortKey);
|
|
786
|
+
const result = await pending;
|
|
787
|
+
|
|
788
|
+
expect((result.error as Error).message).toBe(getErrorMessage("deleted").message);
|
|
789
|
+
expect(rollback).toHaveBeenCalledTimes(1);
|
|
790
|
+
expect(rollback.mock.calls[0][0]).toMatchObject({ reason: "removed" });
|
|
791
|
+
expect(readList()).toStrictEqual(INITIAL_LIST);
|
|
792
|
+
});
|
|
793
|
+
|
|
794
|
+
it("should roll back and resolve when removed while waiting for the network", async () => {
|
|
795
|
+
const { client, mutation, rollback, dispatcher, queryKey, abortKey, responses, readList } = createSetup();
|
|
796
|
+
mockRequest(mutation, { status: 400, delay: 30 });
|
|
797
|
+
let requestId = "";
|
|
798
|
+
|
|
799
|
+
const pending = mutation.send({
|
|
800
|
+
onBeforeSent: (data) => {
|
|
801
|
+
requestId = data.requestId;
|
|
802
|
+
},
|
|
803
|
+
onRequestStart: () => {
|
|
804
|
+
client.appManager.setOnline(false);
|
|
805
|
+
},
|
|
806
|
+
});
|
|
807
|
+
await waitFor(() => {
|
|
808
|
+
expect(responses).toHaveLength(1);
|
|
809
|
+
});
|
|
810
|
+
expect(rollback).not.toHaveBeenCalled();
|
|
811
|
+
|
|
812
|
+
dispatcher.delete(queryKey, requestId, abortKey);
|
|
813
|
+
const result = await pending;
|
|
814
|
+
|
|
815
|
+
expect((result.error as Error).message).toBe(getErrorMessage("deleted").message);
|
|
816
|
+
expect(rollback).toHaveBeenCalledTimes(1);
|
|
817
|
+
expect(rollback.mock.calls[0][0]).toMatchObject({ reason: "removed" });
|
|
818
|
+
expect(readList()).toStrictEqual(INITIAL_LIST);
|
|
819
|
+
});
|
|
820
|
+
|
|
821
|
+
it("should roll back and resolve when aborted while offline", async () => {
|
|
822
|
+
const { client, mutation, rollback } = createSetup();
|
|
823
|
+
mockRequest(mutation, { delay: 100 });
|
|
824
|
+
|
|
825
|
+
const result = await mutation.send({
|
|
826
|
+
onRequestStart: () => {
|
|
827
|
+
client.appManager.setOnline(false);
|
|
828
|
+
mutation.abort();
|
|
829
|
+
},
|
|
830
|
+
});
|
|
831
|
+
|
|
832
|
+
expect((result.error as Error).message).toBe(getErrorMessage("abort").message);
|
|
833
|
+
expect(rollback).toHaveBeenCalledTimes(1);
|
|
834
|
+
expect(rollback.mock.calls[0][0]).toMatchObject({ reason: "abort" });
|
|
835
|
+
});
|
|
836
|
+
|
|
837
|
+
it("should treat offline failure as final when offline mode is disabled", async () => {
|
|
838
|
+
const { client, mutation, rollback } = createSetup();
|
|
839
|
+
const request = mutation.setOffline(false);
|
|
840
|
+
mockRequest(request, { status: 400, delay: 30 });
|
|
841
|
+
|
|
842
|
+
await request.send({
|
|
843
|
+
onRequestStart: () => {
|
|
844
|
+
client.appManager.setOnline(false);
|
|
845
|
+
},
|
|
846
|
+
});
|
|
847
|
+
|
|
848
|
+
expect(rollback).toHaveBeenCalledTimes(1);
|
|
849
|
+
expect(rollback.mock.calls[0][0]).toMatchObject({ reason: "error" });
|
|
850
|
+
});
|
|
851
|
+
|
|
852
|
+
it("should not settle again when stopped request is started later", async () => {
|
|
853
|
+
const { mutation, rollback, invalidate, dispatcher, queryKey, responses } = createSetup();
|
|
854
|
+
mockRequest(mutation, { delay: 50 });
|
|
855
|
+
let requestId = "";
|
|
856
|
+
let isFirstAttempt = true;
|
|
857
|
+
|
|
858
|
+
const result = await mutation.send({
|
|
859
|
+
onRequestStart: (data) => {
|
|
860
|
+
requestId = data.requestId;
|
|
861
|
+
if (isFirstAttempt) {
|
|
862
|
+
isFirstAttempt = false;
|
|
863
|
+
dispatcher.stopRequest(queryKey, requestId);
|
|
864
|
+
}
|
|
865
|
+
},
|
|
866
|
+
});
|
|
867
|
+
|
|
868
|
+
expect((result.error as Error).message).toBe(getErrorMessage("abort").message);
|
|
869
|
+
expect(rollback).toHaveBeenCalledTimes(1);
|
|
870
|
+
expect(rollback.mock.calls[0][0]).toMatchObject({ reason: "abort" });
|
|
871
|
+
|
|
872
|
+
dispatcher.startRequest(queryKey, requestId);
|
|
873
|
+
await waitFor(() => {
|
|
874
|
+
expect(responses).toHaveLength(2);
|
|
875
|
+
});
|
|
876
|
+
|
|
877
|
+
expect(rollback).toHaveBeenCalledTimes(1);
|
|
878
|
+
expect(invalidate).not.toHaveBeenCalled();
|
|
879
|
+
});
|
|
880
|
+
});
|
|
881
|
+
|
|
882
|
+
describe("when multiple mutations are running", () => {
|
|
883
|
+
const createItemMutation = (setup: Setup, item: string) => {
|
|
884
|
+
const rollback = vi.fn(() => {
|
|
885
|
+
setup.removeItem(item);
|
|
886
|
+
});
|
|
887
|
+
const request = setup.client
|
|
888
|
+
.createRequest<{ response: null }>()({ endpoint: `/mutation/${item}`, method: "POST" })
|
|
889
|
+
.setOptimistic(() => {
|
|
890
|
+
setup.addItem(item);
|
|
891
|
+
return { rollback };
|
|
892
|
+
});
|
|
893
|
+
return { request, rollback };
|
|
894
|
+
};
|
|
895
|
+
|
|
896
|
+
it("should roll back only the failed mutation", async () => {
|
|
897
|
+
const setup = createSetup();
|
|
898
|
+
const failed = createItemMutation(setup, "failed");
|
|
899
|
+
const passed = createItemMutation(setup, "passed");
|
|
900
|
+
mockRequest(failed.request, { status: 400, delay: 10 });
|
|
901
|
+
mockRequest(passed.request, { delay: 30 });
|
|
902
|
+
|
|
903
|
+
await Promise.all([failed.request.send(), passed.request.send()]);
|
|
904
|
+
|
|
905
|
+
expect(failed.rollback).toHaveBeenCalledTimes(1);
|
|
906
|
+
expect(passed.rollback).not.toHaveBeenCalled();
|
|
907
|
+
expect(setup.readList()).toStrictEqual([SERVER_ITEM, "passed"]);
|
|
908
|
+
});
|
|
909
|
+
|
|
910
|
+
it("should roll back each failed mutation once", async () => {
|
|
911
|
+
const setup = createSetup();
|
|
912
|
+
const first = createItemMutation(setup, "first");
|
|
913
|
+
const second = createItemMutation(setup, "second");
|
|
914
|
+
mockRequest(first.request, { status: 400, delay: 30 });
|
|
915
|
+
mockRequest(second.request, { status: 500, delay: 10 });
|
|
916
|
+
|
|
917
|
+
await Promise.all([first.request.send(), second.request.send()]);
|
|
918
|
+
|
|
919
|
+
expect(first.rollback).toHaveBeenCalledTimes(1);
|
|
920
|
+
expect(second.rollback).toHaveBeenCalledTimes(1);
|
|
921
|
+
expect(setup.readList()).toStrictEqual(INITIAL_LIST);
|
|
922
|
+
});
|
|
923
|
+
|
|
924
|
+
it("should roll back every send of the same request separately", async () => {
|
|
925
|
+
const setup = createSetup();
|
|
926
|
+
const rollbacks: ReturnType<typeof vi.fn>[] = [];
|
|
927
|
+
const request = setup.client
|
|
928
|
+
.createRequest<{ response: null }>()({ endpoint: "/mutation", method: "POST" })
|
|
929
|
+
.setOptimistic(() => {
|
|
930
|
+
const rollback = vi.fn();
|
|
931
|
+
rollbacks.push(rollback);
|
|
932
|
+
return { rollback };
|
|
933
|
+
});
|
|
934
|
+
mockRequest(request, { status: 400, delay: 10 });
|
|
935
|
+
|
|
936
|
+
await Promise.all([request.send(), request.send()]);
|
|
937
|
+
|
|
938
|
+
expect(rollbacks).toHaveLength(2);
|
|
939
|
+
expect(rollbacks[0]).toHaveBeenCalledTimes(1);
|
|
940
|
+
expect(rollbacks[1]).toHaveBeenCalledTimes(1);
|
|
941
|
+
});
|
|
942
|
+
|
|
943
|
+
it("should roll back every deduplicated send", async () => {
|
|
944
|
+
const setup = createSetup();
|
|
945
|
+
const rollbacks: ReturnType<typeof vi.fn>[] = [];
|
|
946
|
+
const request = setup.client
|
|
947
|
+
.createRequest<{ response: null }>()({ endpoint: "/mutation", method: "POST" })
|
|
948
|
+
.setDeduplicate(true)
|
|
949
|
+
.setOptimistic(() => {
|
|
950
|
+
const rollback = vi.fn();
|
|
951
|
+
rollbacks.push(rollback);
|
|
952
|
+
return { rollback };
|
|
953
|
+
});
|
|
954
|
+
mockRequest(request, { status: 400, delay: 50 });
|
|
955
|
+
|
|
956
|
+
await Promise.all([request.send(), request.send()]);
|
|
957
|
+
|
|
958
|
+
expect(setup.responses).toHaveLength(1);
|
|
959
|
+
expect(rollbacks).toHaveLength(2);
|
|
960
|
+
expect(rollbacks[0]).toHaveBeenCalledTimes(1);
|
|
961
|
+
expect(rollbacks[1]).toHaveBeenCalledTimes(1);
|
|
962
|
+
});
|
|
963
|
+
});
|
|
964
|
+
|
|
965
|
+
describe("when using types", () => {
|
|
966
|
+
const client = new Client({ url: "shared-base-url" });
|
|
967
|
+
const request = client.createRequest<{ response: { id: number }; error: { code: string } }>()({
|
|
968
|
+
endpoint: "/todos",
|
|
969
|
+
method: "POST",
|
|
970
|
+
});
|
|
971
|
+
|
|
972
|
+
it("should type the rollback argument as a union discriminated by reason", () => {
|
|
973
|
+
request.setOptimistic(() => ({
|
|
974
|
+
rollback: (args) => {
|
|
975
|
+
expectTypeOf(args.reason).toEqualTypeOf<"error" | "abort" | "removed">();
|
|
976
|
+
|
|
977
|
+
if (args.reason === "removed") {
|
|
978
|
+
expectTypeOf(args.response).toEqualTypeOf<undefined>();
|
|
979
|
+
} else {
|
|
980
|
+
expectTypeOf(args.response.data).toEqualTypeOf<{ id: number } | null>();
|
|
981
|
+
expectTypeOf(args.response.success).toEqualTypeOf<boolean>();
|
|
982
|
+
}
|
|
983
|
+
},
|
|
984
|
+
}));
|
|
985
|
+
});
|
|
986
|
+
|
|
987
|
+
it("should narrow destructured rollback argument", () => {
|
|
988
|
+
request.setOptimistic(() => ({
|
|
989
|
+
rollback: ({ reason, response }) => {
|
|
990
|
+
if (reason !== "removed") {
|
|
991
|
+
expectTypeOf(response.data).toEqualTypeOf<{ id: number } | null>();
|
|
992
|
+
}
|
|
993
|
+
},
|
|
994
|
+
}));
|
|
995
|
+
});
|
|
996
|
+
|
|
997
|
+
it("should expose the request on the rollback argument", () => {
|
|
998
|
+
request.setOptimistic(() => ({
|
|
999
|
+
rollback: ({ request: sent }) => {
|
|
1000
|
+
expectTypeOf(sent.endpoint).toEqualTypeOf<typeof request.endpoint>();
|
|
1001
|
+
expectTypeOf(sent.method).toEqualTypeOf<typeof request.method>();
|
|
1002
|
+
},
|
|
1003
|
+
}));
|
|
1004
|
+
});
|
|
1005
|
+
|
|
1006
|
+
it("should accept rollback declared without arguments", () => {
|
|
1007
|
+
request.setOptimistic(() => ({ rollback: () => undefined }));
|
|
1008
|
+
});
|
|
1009
|
+
|
|
1010
|
+
it("should expose the argument through the public type", () => {
|
|
1011
|
+
type Args = OptimisticRollbackArgs<typeof request>;
|
|
1012
|
+
|
|
1013
|
+
expectTypeOf<Args["reason"]>().toEqualTypeOf<"error" | "abort" | "removed">();
|
|
1014
|
+
expectTypeOf<Extract<Args, { reason: "removed" }>["response"]>().toEqualTypeOf<undefined>();
|
|
1015
|
+
});
|
|
1016
|
+
|
|
1017
|
+
it("should reject unknown reasons", () => {
|
|
1018
|
+
request.setOptimistic(() => ({
|
|
1019
|
+
rollback: ({ reason }) => {
|
|
1020
|
+
// @ts-expect-error reason is limited to known settlement outcomes
|
|
1021
|
+
const isUnknown = reason === "timeout";
|
|
1022
|
+
return isUnknown ? undefined : undefined;
|
|
1023
|
+
},
|
|
1024
|
+
}));
|
|
1025
|
+
});
|
|
1026
|
+
});
|
|
1027
|
+
});
|