@hyper-fetch/core 9.5.1 → 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.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 +90 -6
- package/dist/index.mjs.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.utils.ts +34 -5
- package/release.config.js +0 -6
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { getErrorMessage } from "adapter";
|
|
2
|
+
import { Client } from "client";
|
|
3
|
+
|
|
4
|
+
describe("Dispatcher [ Retry ]", () => {
|
|
5
|
+
const retryTime = 1000;
|
|
6
|
+
|
|
7
|
+
const createResponse = (success: boolean) => ({
|
|
8
|
+
data: success ? { ok: true } : null,
|
|
9
|
+
error: success ? null : new Error("Request failed"),
|
|
10
|
+
status: success ? 200 : 500,
|
|
11
|
+
success,
|
|
12
|
+
extra: {},
|
|
13
|
+
requestTimestamp: Date.now(),
|
|
14
|
+
responseTimestamp: Date.now(),
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
const deletedResponse = expect.objectContaining({ success: false, error: getErrorMessage("deleted") });
|
|
18
|
+
|
|
19
|
+
let client = new Client({ url: "shared-base-url" });
|
|
20
|
+
let dispatcher = client.fetchDispatcher;
|
|
21
|
+
let fetchSpy = vi.spyOn(client.adapter, "fetch");
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Sends the request and stops right after the first failure, with the retry timer pending
|
|
25
|
+
*/
|
|
26
|
+
const startRetryWait = async (options?: { retry?: number; cancelable?: boolean }) => {
|
|
27
|
+
const request = client.createRequest()({ endpoint: "/retry", retry: 1, retryTime, ...options });
|
|
28
|
+
const onSettled = vi.fn();
|
|
29
|
+
request.send().then(onSettled);
|
|
30
|
+
|
|
31
|
+
await vi.advanceTimersByTimeAsync(0);
|
|
32
|
+
|
|
33
|
+
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
|
34
|
+
const [{ requestId }] = dispatcher.getQueue(request.queryKey).requests;
|
|
35
|
+
|
|
36
|
+
return { request, requestId, queryKey: request.queryKey, onSettled };
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
beforeEach(() => {
|
|
40
|
+
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
|
41
|
+
client = new Client({ url: "shared-base-url" });
|
|
42
|
+
dispatcher = client.fetchDispatcher;
|
|
43
|
+
fetchSpy = vi.spyOn(client.adapter, "fetch").mockImplementation((async () => createResponse(false)) as never);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
afterEach(() => {
|
|
47
|
+
vi.useRealTimers();
|
|
48
|
+
vi.restoreAllMocks();
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
describe("When the request is removed while waiting for the retry", () => {
|
|
52
|
+
it("should not send the retry after deleting the request", async () => {
|
|
53
|
+
const { request, requestId, queryKey, onSettled } = await startRetryWait();
|
|
54
|
+
|
|
55
|
+
dispatcher.delete(queryKey, requestId, request.abortKey);
|
|
56
|
+
await vi.advanceTimersByTimeAsync(retryTime * 2);
|
|
57
|
+
|
|
58
|
+
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
|
59
|
+
expect(onSettled).toHaveBeenCalledExactlyOnceWith(deletedResponse);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it("should not leave the retry timer behind after deleting the request", async () => {
|
|
63
|
+
const { request, requestId, queryKey } = await startRetryWait();
|
|
64
|
+
|
|
65
|
+
dispatcher.delete(queryKey, requestId, request.abortKey);
|
|
66
|
+
|
|
67
|
+
expect(vi.getTimerCount()).toBe(0);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it("should announce the deleted request only once", async () => {
|
|
71
|
+
const onRemove = vi.fn();
|
|
72
|
+
client.requestManager.events.onRemove(onRemove);
|
|
73
|
+
const { request, requestId, queryKey } = await startRetryWait();
|
|
74
|
+
|
|
75
|
+
dispatcher.delete(queryKey, requestId, request.abortKey);
|
|
76
|
+
await vi.advanceTimersByTimeAsync(retryTime * 2);
|
|
77
|
+
|
|
78
|
+
expect(onRemove).toHaveBeenCalledTimes(1);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it("should not send the retry and settle the request after clearing its queue", async () => {
|
|
82
|
+
const onRemove = vi.fn();
|
|
83
|
+
client.requestManager.events.onRemove(onRemove);
|
|
84
|
+
const { requestId, queryKey, onSettled } = await startRetryWait();
|
|
85
|
+
|
|
86
|
+
dispatcher.clearQueue(queryKey);
|
|
87
|
+
await vi.advanceTimersByTimeAsync(0);
|
|
88
|
+
|
|
89
|
+
expect(onSettled).toHaveBeenCalledExactlyOnceWith(deletedResponse);
|
|
90
|
+
|
|
91
|
+
await vi.advanceTimersByTimeAsync(retryTime * 2);
|
|
92
|
+
|
|
93
|
+
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
|
94
|
+
expect(onRemove).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ requestId }));
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("should not send the retry and settle the request after clearing the dispatcher", async () => {
|
|
98
|
+
const onRemove = vi.fn();
|
|
99
|
+
client.requestManager.events.onRemove(onRemove);
|
|
100
|
+
const { requestId, onSettled } = await startRetryWait();
|
|
101
|
+
|
|
102
|
+
dispatcher.clear();
|
|
103
|
+
await vi.advanceTimersByTimeAsync(0);
|
|
104
|
+
|
|
105
|
+
expect(onSettled).toHaveBeenCalledExactlyOnceWith(deletedResponse);
|
|
106
|
+
|
|
107
|
+
await vi.advanceTimersByTimeAsync(retryTime * 2);
|
|
108
|
+
|
|
109
|
+
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
|
110
|
+
expect(onRemove).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ requestId }));
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it("should not send the retry of a request replaced by a cancelable one", async () => {
|
|
114
|
+
const { request, onSettled } = await startRetryWait({ cancelable: true });
|
|
115
|
+
fetchSpy.mockImplementationOnce((async () => createResponse(true)) as never);
|
|
116
|
+
|
|
117
|
+
const replacement = request.clone();
|
|
118
|
+
const onReplacementSettled = vi.fn();
|
|
119
|
+
replacement.send().then(onReplacementSettled);
|
|
120
|
+
await vi.advanceTimersByTimeAsync(retryTime * 2);
|
|
121
|
+
|
|
122
|
+
expect(fetchSpy).toHaveBeenCalledTimes(2);
|
|
123
|
+
expect(onSettled).toHaveBeenCalledExactlyOnceWith(deletedResponse);
|
|
124
|
+
expect(onReplacementSettled).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ success: true }));
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it("should not send the retry when the request disappeared from the storage", async () => {
|
|
128
|
+
const onRemove = vi.fn();
|
|
129
|
+
client.requestManager.events.onRemove(onRemove);
|
|
130
|
+
const { requestId, queryKey, onSettled } = await startRetryWait();
|
|
131
|
+
|
|
132
|
+
dispatcher.storage.delete(queryKey);
|
|
133
|
+
await vi.advanceTimersByTimeAsync(retryTime * 2);
|
|
134
|
+
|
|
135
|
+
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
|
136
|
+
expect(onSettled).toHaveBeenCalledExactlyOnceWith(deletedResponse);
|
|
137
|
+
expect(onRemove).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ requestId }));
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
describe("When the request stays in the queue while waiting for the retry", () => {
|
|
142
|
+
it("should send the retry once the retry time passes", async () => {
|
|
143
|
+
const { onSettled } = await startRetryWait();
|
|
144
|
+
fetchSpy.mockImplementationOnce((async () => createResponse(true)) as never);
|
|
145
|
+
|
|
146
|
+
await vi.advanceTimersByTimeAsync(retryTime - 1);
|
|
147
|
+
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
|
148
|
+
|
|
149
|
+
await vi.advanceTimersByTimeAsync(1);
|
|
150
|
+
expect(fetchSpy).toHaveBeenCalledTimes(2);
|
|
151
|
+
expect(onSettled).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ success: true }));
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it("should use all of the available retries and remove the request afterwards", async () => {
|
|
155
|
+
const { queryKey, onSettled } = await startRetryWait({ retry: 2 });
|
|
156
|
+
|
|
157
|
+
await vi.advanceTimersByTimeAsync(retryTime * 2);
|
|
158
|
+
|
|
159
|
+
expect(fetchSpy).toHaveBeenCalledTimes(3);
|
|
160
|
+
expect(dispatcher.getQueue(queryKey).requests).toHaveLength(0);
|
|
161
|
+
expect(onSettled).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ success: false }));
|
|
162
|
+
expect(vi.getTimerCount()).toBe(0);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it("should send the retry when the queue gets paused during the wait", async () => {
|
|
166
|
+
const { queryKey, onSettled } = await startRetryWait();
|
|
167
|
+
fetchSpy.mockImplementationOnce((async () => createResponse(true)) as never);
|
|
168
|
+
|
|
169
|
+
dispatcher.pause(queryKey);
|
|
170
|
+
await vi.advanceTimersByTimeAsync(retryTime);
|
|
171
|
+
|
|
172
|
+
expect(fetchSpy).toHaveBeenCalledTimes(2);
|
|
173
|
+
expect(onSettled).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ success: true }));
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it("should send the retry when the queue gets stopped during the wait", async () => {
|
|
177
|
+
const { queryKey, onSettled } = await startRetryWait();
|
|
178
|
+
fetchSpy.mockImplementationOnce((async () => createResponse(true)) as never);
|
|
179
|
+
|
|
180
|
+
dispatcher.stop(queryKey);
|
|
181
|
+
await vi.advanceTimersByTimeAsync(retryTime);
|
|
182
|
+
|
|
183
|
+
expect(fetchSpy).toHaveBeenCalledTimes(2);
|
|
184
|
+
expect(onSettled).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ success: true }));
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
it("should hold the retry of a stopped request until it gets started again", async () => {
|
|
188
|
+
const { requestId, queryKey, onSettled } = await startRetryWait();
|
|
189
|
+
fetchSpy.mockImplementationOnce((async () => createResponse(true)) as never);
|
|
190
|
+
|
|
191
|
+
dispatcher.stopRequest(queryKey, requestId);
|
|
192
|
+
await vi.advanceTimersByTimeAsync(retryTime * 2);
|
|
193
|
+
|
|
194
|
+
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
|
195
|
+
expect(dispatcher.getRequest(queryKey, requestId)).toBeDefined();
|
|
196
|
+
expect(onSettled).not.toHaveBeenCalled();
|
|
197
|
+
|
|
198
|
+
dispatcher.startRequest(queryKey, requestId);
|
|
199
|
+
await vi.advanceTimersByTimeAsync(0);
|
|
200
|
+
|
|
201
|
+
expect(fetchSpy).toHaveBeenCalledTimes(2);
|
|
202
|
+
expect(onSettled).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ success: true }));
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it("should keep a single retry timer when the queue is flushed during the wait", async () => {
|
|
206
|
+
const { queryKey } = await startRetryWait();
|
|
207
|
+
|
|
208
|
+
dispatcher.start(queryKey);
|
|
209
|
+
await vi.advanceTimersByTimeAsync(0);
|
|
210
|
+
|
|
211
|
+
expect(fetchSpy).toHaveBeenCalledTimes(2);
|
|
212
|
+
expect(vi.getTimerCount()).toBe(1);
|
|
213
|
+
|
|
214
|
+
await vi.advanceTimersByTimeAsync(retryTime * 2);
|
|
215
|
+
|
|
216
|
+
expect(fetchSpy).toHaveBeenCalledTimes(3);
|
|
217
|
+
expect(dispatcher.getQueue(queryKey).requests).toHaveLength(0);
|
|
218
|
+
});
|
|
219
|
+
});
|
|
220
|
+
});
|
|
@@ -0,0 +1,362 @@
|
|
|
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 { OptimisticRollbackArgs } from "request";
|
|
6
|
+
import { scopeKey } from "request";
|
|
7
|
+
|
|
8
|
+
const { resetMocks, startServer, stopServer, mockRequest } = createHttpMockingServer();
|
|
9
|
+
|
|
10
|
+
const MAPPER_ERROR = new Error("Mapper failed");
|
|
11
|
+
const SERVER_ITEM = "server";
|
|
12
|
+
const OPTIMISTIC_ITEM = "optimistic";
|
|
13
|
+
const INITIAL_LIST = [SERVER_ITEM];
|
|
14
|
+
|
|
15
|
+
// Failing mappers keep the response type, otherwise the mapped request would be typed with `never`
|
|
16
|
+
type FailingMapper = <Response>(response: Response) => Response | Promise<Response>;
|
|
17
|
+
|
|
18
|
+
const rejectingMapper: FailingMapper = async () => {
|
|
19
|
+
throw MAPPER_ERROR;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const throwingMapper: FailingMapper = () => {
|
|
23
|
+
throw MAPPER_ERROR;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const failures = [
|
|
27
|
+
{ name: "rejects", mapper: rejectingMapper },
|
|
28
|
+
{ name: "throws synchronously", mapper: throwingMapper },
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Builds isolated client with a seeded list and a mutation which adds one item to it optimistically
|
|
33
|
+
*/
|
|
34
|
+
const createSetup = () => {
|
|
35
|
+
const client = new Client({ url: "shared-base-url" });
|
|
36
|
+
const list = client.createRequest<{ response: string[] }>()({ endpoint: "/list" });
|
|
37
|
+
|
|
38
|
+
client.cache.set(list, {
|
|
39
|
+
data: INITIAL_LIST,
|
|
40
|
+
error: null,
|
|
41
|
+
status: 200,
|
|
42
|
+
success: true,
|
|
43
|
+
extra: client.adapter.defaultExtra,
|
|
44
|
+
retries: 0,
|
|
45
|
+
isCanceled: false,
|
|
46
|
+
isOffline: false,
|
|
47
|
+
willRetry: false,
|
|
48
|
+
addedTimestamp: Date.now(),
|
|
49
|
+
triggerTimestamp: Date.now(),
|
|
50
|
+
requestTimestamp: Date.now(),
|
|
51
|
+
// Garbage collector drops the entries with outdated timestamps
|
|
52
|
+
responseTimestamp: Date.now(),
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
const readList = () => client.cache.get<string[], unknown>(list.cacheKey)?.data;
|
|
56
|
+
|
|
57
|
+
const rollback = vi.fn((_args: OptimisticRollbackArgs<any>) => {
|
|
58
|
+
client.cache.update(list, (prev) => ({
|
|
59
|
+
data: (prev?.data ?? []).filter((value) => value !== OPTIMISTIC_ITEM),
|
|
60
|
+
}));
|
|
61
|
+
});
|
|
62
|
+
const invalidate = vi.spyOn(client.cache, "invalidate");
|
|
63
|
+
const logError = vi.spyOn(client.logger, "error");
|
|
64
|
+
|
|
65
|
+
const request = client.createRequest<{ response: { ok: boolean } }>()({ endpoint: "/mutation", method: "POST" });
|
|
66
|
+
const mutation = request.setOptimistic(() => {
|
|
67
|
+
client.cache.update(list, (prev) => ({ data: [...(prev?.data ?? []), OPTIMISTIC_ITEM] }));
|
|
68
|
+
return { rollback, invalidate: [list] };
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
const getListeners = (requestId: string) => {
|
|
72
|
+
return client.requestManager.emitter.eventNames().filter((name) => String(name).includes(requestId));
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
return { client, list, request, mutation, rollback, invalidate, logError, readList, getListeners };
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
describe("Request [ Response mapper failure ]", () => {
|
|
79
|
+
beforeAll(() => {
|
|
80
|
+
startServer();
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
afterEach(() => {
|
|
84
|
+
resetMocks();
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
afterAll(() => {
|
|
88
|
+
stopServer();
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
describe.each(failures)("when the mapper $name", ({ mapper }) => {
|
|
92
|
+
it("should resolve with failed response carrying the mapper error", async () => {
|
|
93
|
+
const { request } = createSetup();
|
|
94
|
+
const mapped = request.setResponseMapper(mapper);
|
|
95
|
+
mockRequest(mapped, { data: { ok: true }, status: 200 });
|
|
96
|
+
|
|
97
|
+
const result = await mapped.send();
|
|
98
|
+
|
|
99
|
+
expect(result.success).toBe(false);
|
|
100
|
+
expect(result.data).toBeNull();
|
|
101
|
+
expect(result.error).toBe(MAPPER_ERROR);
|
|
102
|
+
expect(result.status).toBe(200);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it("should log the failure once", async () => {
|
|
106
|
+
const { request, logError } = createSetup();
|
|
107
|
+
const mapped = request.setResponseMapper(mapper);
|
|
108
|
+
mockRequest(mapped);
|
|
109
|
+
|
|
110
|
+
await mapped.send();
|
|
111
|
+
|
|
112
|
+
const logs = logError.mock.calls.filter(([log]) => log.title === "Response mapper failed");
|
|
113
|
+
expect(logs).toHaveLength(1);
|
|
114
|
+
expect(logs[0][0].extra).toMatchObject({ error: MAPPER_ERROR });
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("should clean up the listeners", async () => {
|
|
118
|
+
const { request, getListeners } = createSetup();
|
|
119
|
+
const mapped = request.setResponseMapper(mapper);
|
|
120
|
+
mockRequest(mapped);
|
|
121
|
+
let requestId = "";
|
|
122
|
+
let attachedListeners = 0;
|
|
123
|
+
|
|
124
|
+
await mapped.send({
|
|
125
|
+
onBeforeSent: (data) => {
|
|
126
|
+
requestId = data.requestId;
|
|
127
|
+
},
|
|
128
|
+
onRequestStart: () => {
|
|
129
|
+
attachedListeners = getListeners(requestId).length;
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
expect(attachedListeners).toBeGreaterThan(0);
|
|
134
|
+
expect(getListeners(requestId)).toHaveLength(0);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it("should notify about the response once", async () => {
|
|
138
|
+
const { request } = createSetup();
|
|
139
|
+
const mapped = request.setResponseMapper(mapper);
|
|
140
|
+
mockRequest(mapped);
|
|
141
|
+
const onResponse = vi.fn();
|
|
142
|
+
|
|
143
|
+
await mapped.send({ onResponse });
|
|
144
|
+
|
|
145
|
+
expect(onResponse).toHaveBeenCalledTimes(1);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("should roll back the optimistic change once with error reason", async () => {
|
|
149
|
+
const { mutation, rollback, invalidate, readList } = createSetup();
|
|
150
|
+
const mapped = mutation.setResponseMapper(mapper);
|
|
151
|
+
mockRequest(mapped, { data: { ok: true } });
|
|
152
|
+
|
|
153
|
+
const result = await mapped.send();
|
|
154
|
+
|
|
155
|
+
expect(rollback).toHaveBeenCalledTimes(1);
|
|
156
|
+
expect(rollback.mock.calls[0][0]).toMatchObject({ reason: "error" });
|
|
157
|
+
expect(rollback.mock.calls[0][0].response?.error).toBe(MAPPER_ERROR);
|
|
158
|
+
expect(result.error).toBe(MAPPER_ERROR);
|
|
159
|
+
expect(readList()).toEqual(INITIAL_LIST);
|
|
160
|
+
expect(invalidate).not.toHaveBeenCalled();
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it("should roll back aborted request with abort reason", async () => {
|
|
164
|
+
const { mutation, rollback } = createSetup();
|
|
165
|
+
const mapped = mutation.setResponseMapper(mapper);
|
|
166
|
+
mockRequest(mapped, { delay: 100 });
|
|
167
|
+
|
|
168
|
+
const result = await mapped.send({
|
|
169
|
+
onRequestStart: () => {
|
|
170
|
+
mapped.abort();
|
|
171
|
+
},
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
expect(result.success).toBe(false);
|
|
175
|
+
expect(rollback).toHaveBeenCalledTimes(1);
|
|
176
|
+
expect(rollback.mock.calls[0][0]).toMatchObject({ reason: "abort" });
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it("should roll back once after the retries are used up", async () => {
|
|
180
|
+
const { client, mutation, rollback } = createSetup();
|
|
181
|
+
let attempts = 0;
|
|
182
|
+
const failingMapper: FailingMapper = (response) => {
|
|
183
|
+
attempts += 1;
|
|
184
|
+
return mapper(response);
|
|
185
|
+
};
|
|
186
|
+
const mapped = mutation.setRetry(1).setRetryTime(10).setResponseMapper(failingMapper);
|
|
187
|
+
mockRequest(mapped, { status: 400 });
|
|
188
|
+
const onResponse = vi.fn();
|
|
189
|
+
client.requestManager.events.onResponse(onResponse);
|
|
190
|
+
|
|
191
|
+
const result = await mapped.send();
|
|
192
|
+
|
|
193
|
+
expect(onResponse).toHaveBeenCalledTimes(2);
|
|
194
|
+
expect(attempts).toBe(2);
|
|
195
|
+
expect(result.error).toBe(MAPPER_ERROR);
|
|
196
|
+
expect(rollback).toHaveBeenCalledTimes(1);
|
|
197
|
+
expect(rollback.mock.calls[0][0]).toMatchObject({ reason: "error" });
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it("should wait for the retry when the failed attempt can't be mapped", async () => {
|
|
201
|
+
const { client, mutation, rollback, invalidate, list } = createSetup();
|
|
202
|
+
let attempts = 0;
|
|
203
|
+
const failingOnceMapper: FailingMapper = (response) => {
|
|
204
|
+
attempts += 1;
|
|
205
|
+
return attempts === 1 ? mapper(response) : response;
|
|
206
|
+
};
|
|
207
|
+
const mapped = mutation.setRetry(1).setRetryTime(10).setResponseMapper(failingOnceMapper);
|
|
208
|
+
mockRequest(mapped, { status: 400 });
|
|
209
|
+
const unmount = client.requestManager.events.onResponse(() => {
|
|
210
|
+
unmount();
|
|
211
|
+
mockRequest(mapped, { data: { ok: true } });
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
const result = await mapped.send();
|
|
215
|
+
|
|
216
|
+
expect(result.success).toBe(true);
|
|
217
|
+
expect(result.error).toBeNull();
|
|
218
|
+
expect(rollback).not.toHaveBeenCalled();
|
|
219
|
+
expect(invalidate).toHaveBeenCalledWith(list);
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
it("should wait for the reconnection when the offline attempt can't be mapped", async () => {
|
|
223
|
+
const { client, mutation, rollback, invalidate, list } = createSetup();
|
|
224
|
+
let attempts = 0;
|
|
225
|
+
const failingOnceMapper: FailingMapper = (response) => {
|
|
226
|
+
attempts += 1;
|
|
227
|
+
return attempts === 1 ? mapper(response) : response;
|
|
228
|
+
};
|
|
229
|
+
const mapped = mutation.setResponseMapper(failingOnceMapper);
|
|
230
|
+
mockRequest(mapped, { status: 400, delay: 30 });
|
|
231
|
+
const onAttempt = vi.fn();
|
|
232
|
+
const unmount = client.requestManager.events.onResponse(() => {
|
|
233
|
+
unmount();
|
|
234
|
+
mockRequest(mapped, { data: { ok: true } });
|
|
235
|
+
onAttempt();
|
|
236
|
+
});
|
|
237
|
+
let isFirstAttempt = true;
|
|
238
|
+
|
|
239
|
+
const pending = mapped.send({
|
|
240
|
+
onRequestStart: () => {
|
|
241
|
+
if (isFirstAttempt) {
|
|
242
|
+
isFirstAttempt = false;
|
|
243
|
+
client.appManager.setOnline(false);
|
|
244
|
+
}
|
|
245
|
+
},
|
|
246
|
+
});
|
|
247
|
+
await waitFor(() => {
|
|
248
|
+
expect(onAttempt).toHaveBeenCalledTimes(1);
|
|
249
|
+
});
|
|
250
|
+
expect(rollback).not.toHaveBeenCalled();
|
|
251
|
+
|
|
252
|
+
client.appManager.setOnline(true);
|
|
253
|
+
const result = await pending;
|
|
254
|
+
|
|
255
|
+
expect(result.success).toBe(true);
|
|
256
|
+
expect(rollback).not.toHaveBeenCalled();
|
|
257
|
+
expect(invalidate).toHaveBeenCalledWith(list);
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it.each(["cache-first", "revalidate"] as const)(
|
|
261
|
+
"should resolve with failed response for cached data with %s policy",
|
|
262
|
+
async (cachePolicy) => {
|
|
263
|
+
const { request, client, logError } = createSetup();
|
|
264
|
+
const mapped = request.setResponseMapper(mapper);
|
|
265
|
+
mockRequest(mapped, { data: { ok: true } });
|
|
266
|
+
client.cache.set(mapped, {
|
|
267
|
+
data: { ok: true },
|
|
268
|
+
error: null,
|
|
269
|
+
status: 200,
|
|
270
|
+
success: true,
|
|
271
|
+
extra: client.adapter.defaultExtra,
|
|
272
|
+
retries: 0,
|
|
273
|
+
isCanceled: false,
|
|
274
|
+
isOffline: false,
|
|
275
|
+
willRetry: false,
|
|
276
|
+
addedTimestamp: Date.now(),
|
|
277
|
+
triggerTimestamp: Date.now(),
|
|
278
|
+
requestTimestamp: Date.now(),
|
|
279
|
+
responseTimestamp: Date.now(),
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
const result = await mapped.send({ cachePolicy });
|
|
283
|
+
|
|
284
|
+
expect(result.success).toBe(false);
|
|
285
|
+
expect(result.error).toBe(MAPPER_ERROR);
|
|
286
|
+
await waitFor(() => {
|
|
287
|
+
expect(logError).toHaveBeenCalled();
|
|
288
|
+
});
|
|
289
|
+
},
|
|
290
|
+
);
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
describe("when the mapper rejects with non-error value", () => {
|
|
294
|
+
it("should carry the value as it is", async () => {
|
|
295
|
+
const { request } = createSetup();
|
|
296
|
+
const reason = { code: "INVALID_SHAPE" };
|
|
297
|
+
const failingMapper: FailingMapper = async () => {
|
|
298
|
+
// eslint-disable-next-line @typescript-eslint/only-throw-error
|
|
299
|
+
throw reason;
|
|
300
|
+
};
|
|
301
|
+
const mapped = request.setResponseMapper(failingMapper);
|
|
302
|
+
mockRequest(mapped);
|
|
303
|
+
|
|
304
|
+
const result = await mapped.send();
|
|
305
|
+
|
|
306
|
+
expect(result.success).toBe(false);
|
|
307
|
+
expect(result.error).toBe(reason);
|
|
308
|
+
});
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
describe("when the request gets removed before the mapper rejects", () => {
|
|
312
|
+
it("should settle only with the removal", async () => {
|
|
313
|
+
const { client, mutation, rollback, invalidate } = createSetup();
|
|
314
|
+
const dispatcher = client.submitDispatcher;
|
|
315
|
+
// The retry timer is not part of this case
|
|
316
|
+
vi.spyOn(dispatcher, "performRequest");
|
|
317
|
+
let release: VoidFunction = () => undefined;
|
|
318
|
+
const gate = new Promise<void>((resolve) => {
|
|
319
|
+
release = resolve;
|
|
320
|
+
});
|
|
321
|
+
let mapping: Promise<never> | undefined;
|
|
322
|
+
const mapper: FailingMapper = () => {
|
|
323
|
+
mapping = gate.then(() => {
|
|
324
|
+
throw MAPPER_ERROR;
|
|
325
|
+
});
|
|
326
|
+
return mapping;
|
|
327
|
+
};
|
|
328
|
+
const mapped = mutation.setRetry(1).setRetryTime(50).setResponseMapper(mapper);
|
|
329
|
+
mockRequest(mapped, { status: 400 });
|
|
330
|
+
const onResponse = vi.fn();
|
|
331
|
+
const onAttempt = vi.fn();
|
|
332
|
+
client.requestManager.events.onResponse(onAttempt);
|
|
333
|
+
let requestId = "";
|
|
334
|
+
|
|
335
|
+
const pending = mapped.send({
|
|
336
|
+
onBeforeSent: (data) => {
|
|
337
|
+
requestId = data.requestId;
|
|
338
|
+
},
|
|
339
|
+
onResponse,
|
|
340
|
+
});
|
|
341
|
+
await waitFor(() => {
|
|
342
|
+
expect(onAttempt).toHaveBeenCalledTimes(1);
|
|
343
|
+
});
|
|
344
|
+
vi.mocked(dispatcher.performRequest).mockImplementation(async () => undefined);
|
|
345
|
+
|
|
346
|
+
dispatcher.delete(scopeKey(mapped.queryKey, mapped.scope), requestId, scopeKey(mapped.abortKey, mapped.scope));
|
|
347
|
+
const result = await pending;
|
|
348
|
+
release();
|
|
349
|
+
await expect(mapping).rejects.toBe(MAPPER_ERROR);
|
|
350
|
+
// Handlers of the rejection run after the promise above is settled
|
|
351
|
+
await new Promise((resolve) => {
|
|
352
|
+
setTimeout(resolve, 0);
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
expect((result.error as Error).message).toBe(getErrorMessage("deleted").message);
|
|
356
|
+
expect(rollback).toHaveBeenCalledTimes(1);
|
|
357
|
+
expect(rollback.mock.calls[0][0]).toMatchObject({ reason: "removed" });
|
|
358
|
+
expect(invalidate).not.toHaveBeenCalled();
|
|
359
|
+
expect(onResponse).not.toHaveBeenCalled();
|
|
360
|
+
});
|
|
361
|
+
});
|
|
362
|
+
});
|
|
@@ -28,6 +28,7 @@ export declare class Dispatcher<Adapter extends AdapterInstance> {
|
|
|
28
28
|
storage: DispatcherStorageType;
|
|
29
29
|
private requestCount;
|
|
30
30
|
private runningRequests;
|
|
31
|
+
private retryTimers;
|
|
31
32
|
private logger;
|
|
32
33
|
private client;
|
|
33
34
|
constructor(options?: DispatcherOptionsType | undefined);
|
|
@@ -94,6 +95,15 @@ export declare class Dispatcher<Adapter extends AdapterInstance> {
|
|
|
94
95
|
* Clear all running requests and storage
|
|
95
96
|
*/
|
|
96
97
|
clear: () => void;
|
|
98
|
+
/**
|
|
99
|
+
* Drop the scheduled retry of the request
|
|
100
|
+
*/
|
|
101
|
+
private cancelRetry;
|
|
102
|
+
/**
|
|
103
|
+
* Clearing does not announce removed items. Requests waiting for a retry have no attempt left to end with,
|
|
104
|
+
* so without this event their listeners would never be notified.
|
|
105
|
+
*/
|
|
106
|
+
private removeWaitingRetries;
|
|
97
107
|
/**
|
|
98
108
|
* Start particular request
|
|
99
109
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dispatcher.d.ts","sourceRoot":"","sources":["../../src/dispatcher/dispatcher.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAuB,MAAM,SAAS,CAAC;AAEpE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAC7C,OAAO,KAAK,EACV,aAAa,EACb,qBAAqB,EACrB,qBAAqB,EACrB,qBAAqB,EACrB,qBAAqB,EACrB,uBAAuB,EACxB,MAAM,YAAY,CAAC;AAGpB,OAAO,KAAK,EAAE,eAAe,EAAe,MAAM,SAAS,CAAC;AAE5D,OAAO,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAErC;;;;GAIG;AACH,qBAAa,UAAU,CAAC,OAAO,SAAS,eAAe;
|
|
1
|
+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