@hyper-fetch/core 9.5.1 → 9.6.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.
@@ -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,213 @@
1
+ import { Client, fetchInfinite } from "@hyper-fetch/core";
2
+ import { createHttpMockingServer } from "@hyper-fetch/testing";
3
+ import { http, HttpResponse } from "msw";
4
+
5
+ const baseUrl = "http://localhost:3000";
6
+
7
+ type Post = { id: number };
8
+
9
+ describe("Infinite [ fetchInfinite ]", () => {
10
+ const { server, startServer, stopServer, resetMocks } = createHttpMockingServer();
11
+ const calls: Record<string, string>[] = [];
12
+
13
+ let client: Client;
14
+
15
+ const createPosts = () =>
16
+ client.createRequest<{ response: Post[]; queryParams: { page?: number; limit?: number; search?: string } }>()({
17
+ endpoint: "/posts",
18
+ });
19
+
20
+ const createFeed = () =>
21
+ client.createRequest<{
22
+ response: { data: Post[]; next: string | null; total: number };
23
+ queryParams: { cursor?: string };
24
+ }>()({ endpoint: "/feed" });
25
+
26
+ const mock = (path: string, handler: (query: Record<string, string>) => unknown, status = 200) => {
27
+ server.use(
28
+ http.get(`${baseUrl}${path}`, ({ request }) => {
29
+ const query = Object.fromEntries(new URL(request.url).searchParams.entries());
30
+ calls.push(query);
31
+ return HttpResponse.json(handler(query) as any, { status });
32
+ }),
33
+ );
34
+ };
35
+
36
+ const mockPosts = (lastPage = 9) => {
37
+ mock("/posts", ({ page }) => (Number(page) > lastPage ? [] : [{ id: Number(page) }]));
38
+ };
39
+
40
+ beforeAll(() => startServer());
41
+ afterAll(() => stopServer());
42
+
43
+ beforeEach(() => {
44
+ client = new Client({ url: baseUrl });
45
+ calls.length = 0;
46
+ });
47
+
48
+ afterEach(() => resetMocks());
49
+
50
+ it("should fetch only the first page by default", async () => {
51
+ mockPosts();
52
+
53
+ const result = await fetchInfinite(createPosts(), { pagination: { page: "page" } });
54
+
55
+ expect(calls).toEqual([{ page: "1" }]);
56
+ expect(result.items).toEqual([{ id: 1 }]);
57
+ expect(result.pages).toEqual([[{ id: 1 }]]);
58
+ expect(result.pageParams).toEqual([1]);
59
+ expect(result.hasNextPage).toBe(true);
60
+ expect(result.error).toBeNull();
61
+ });
62
+
63
+ it.each([0, -3])("should fetch one page when asked for %s pages", async (pages) => {
64
+ mockPosts();
65
+
66
+ const result = await fetchInfinite(createPosts(), { pagination: { page: "page" }, pages });
67
+
68
+ expect(result.pages).toHaveLength(1);
69
+ });
70
+
71
+ it("should fetch the pages one after another", async () => {
72
+ mockPosts();
73
+
74
+ const result = await fetchInfinite(createPosts(), { pagination: { page: "page" }, pages: 3 });
75
+
76
+ expect(calls.map((call) => call.page)).toEqual(["1", "2", "3"]);
77
+ expect(result.items).toEqual([{ id: 1 }, { id: 2 }, { id: 3 }]);
78
+ expect(result.responses).toHaveLength(3);
79
+ });
80
+
81
+ it("should start from the page set on the request and keep other query params", async () => {
82
+ mockPosts();
83
+
84
+ const result = await fetchInfinite(createPosts().setQueryParams({ page: 4, search: "a" }), {
85
+ pagination: { page: "page" },
86
+ pages: 2,
87
+ });
88
+
89
+ expect(calls).toEqual([
90
+ { page: "4", search: "a" },
91
+ { page: "5", search: "a" },
92
+ ]);
93
+ expect(result.pageParams).toEqual([4, 5]);
94
+ });
95
+
96
+ it("should stop at the end of the list", async () => {
97
+ mockPosts(1);
98
+
99
+ const result = await fetchInfinite(createPosts(), { pagination: { page: "page" }, pages: 9 });
100
+
101
+ expect(calls).toHaveLength(2);
102
+ expect(result.hasNextPage).toBe(false);
103
+ expect(result.items).toEqual([{ id: 1 }]);
104
+ });
105
+
106
+ it("should follow cursors and read the total", async () => {
107
+ mock("/feed", ({ cursor }) => {
108
+ return cursor ? { data: [{ id: 2 }], next: null, total: 2 } : { data: [{ id: 1 }], next: "second", total: 2 };
109
+ });
110
+
111
+ const result = await fetchInfinite(createFeed(), {
112
+ pagination: { cursor: "cursor", next: "next", items: "data", total: "total" },
113
+ pages: 5,
114
+ });
115
+
116
+ expect(calls).toEqual([{}, { cursor: "second" }]);
117
+ expect(result.items).toEqual([{ id: 1 }, { id: 2 }]);
118
+ expect(result.pageParams).toEqual([undefined, "second"]);
119
+ expect(result.total).toBe(2);
120
+ expect(result.hasNextPage).toBe(false);
121
+ });
122
+
123
+ it("should keep the last known total when a page does not report it", async () => {
124
+ mock("/feed", ({ cursor }) => {
125
+ return cursor ? { data: [], next: null } : { data: [{ id: 1 }], next: "second", total: 7 };
126
+ });
127
+
128
+ const result = await fetchInfinite(createFeed(), {
129
+ pagination: { cursor: "cursor", next: "next", items: "data", total: "total" },
130
+ pages: 2,
131
+ });
132
+
133
+ expect(result.total).toBe(7);
134
+ });
135
+
136
+ it("should stop on a failed first page", async () => {
137
+ mock("/posts", () => ({ message: "Failed" }), 500);
138
+
139
+ const result = await fetchInfinite(createPosts(), { pagination: { page: "page" }, pages: 3 });
140
+
141
+ expect(calls).toHaveLength(1);
142
+ expect(result.error).toEqual({ message: "Failed" });
143
+ expect(result.items).toEqual([]);
144
+ expect(result.pages).toEqual([]);
145
+ expect(result.dehydrated).toEqual([]);
146
+ expect(result.responses).toHaveLength(1);
147
+ expect(result.hasNextPage).toBe(false);
148
+ });
149
+
150
+ it("should keep the pages fetched before a failure", async () => {
151
+ server.use(
152
+ http.get(`${baseUrl}/posts`, ({ request }) => {
153
+ const page = new URL(request.url).searchParams.get("page");
154
+ return page === "1"
155
+ ? HttpResponse.json([{ id: 1 }])
156
+ : HttpResponse.json({ message: "Failed" }, { status: 500 });
157
+ }),
158
+ );
159
+
160
+ const result = await fetchInfinite(createPosts(), { pagination: { page: "page" }, pages: 3 });
161
+
162
+ expect(result.items).toEqual([{ id: 1 }]);
163
+ expect(result.dehydrated).toHaveLength(1);
164
+ expect(result.error).toEqual({ message: "Failed" });
165
+ });
166
+
167
+ it("should dehydrate every page under its own cache key", async () => {
168
+ mockPosts();
169
+
170
+ const { dehydrated } = await fetchInfinite(createPosts(), { pagination: { page: "page" }, pages: 2 });
171
+
172
+ expect(dehydrated.map((item) => item.cacheKey)).toEqual([
173
+ createPosts().setQueryParams({ page: 1 }).cacheKey,
174
+ createPosts().setQueryParams({ page: 2 }).cacheKey,
175
+ ]);
176
+ expect(dehydrated[1].response.data).toEqual([{ id: 2 }]);
177
+ });
178
+
179
+ it("should keep the scope in the dehydrated pages", async () => {
180
+ mockPosts();
181
+
182
+ const { dehydrated } = await fetchInfinite(createPosts().setScope("user"), { pagination: { page: "page" } });
183
+
184
+ expect(dehydrated[0].scope).toBe("user");
185
+ });
186
+
187
+ it("should fill the cache only after hydrating", async () => {
188
+ mockPosts();
189
+
190
+ const { dehydrated } = await fetchInfinite(createPosts(), { pagination: { page: "page" }, pages: 2 });
191
+
192
+ expect(client.cache.keys()).toHaveLength(0);
193
+
194
+ client.hydrate(dehydrated);
195
+
196
+ expect(client.cache.keys()).toHaveLength(2);
197
+ expect(createPosts().setQueryParams({ page: 2 }).read()?.data).toEqual([{ id: 2 }]);
198
+ });
199
+
200
+ it("should not use the queues", async () => {
201
+ mockPosts();
202
+ const add = vi.spyOn(client.fetchDispatcher, "add");
203
+
204
+ await fetchInfinite(createPosts(), { pagination: { page: "page" }, pages: 2 });
205
+
206
+ expect(add).not.toHaveBeenCalled();
207
+ });
208
+
209
+ it("should explain a missing pagination", async () => {
210
+ await expect(fetchInfinite(createPosts(), {} as any)).rejects.toThrow('"pagination" option');
211
+ expect(calls).toHaveLength(0);
212
+ });
213
+ });