@hyper-fetch/core 10.4.0 → 10.5.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.
Files changed (36) hide show
  1. package/__tests__/features/adapter/adapter.mapping.spec.ts +29 -1
  2. package/__tests__/features/cache/cache.modes.spec.ts +33 -0
  3. package/__tests__/features/client/client.configuration.spec.ts +24 -0
  4. package/__tests__/features/request/request.exec.spec.ts +129 -0
  5. package/__tests__/features/request/request.signal.spec.ts +243 -0
  6. package/__tests__/features/request/request.throw-on-error.spec.ts +219 -0
  7. package/__tests__/features/request/request.typescript.spec.ts +46 -0
  8. package/dist/adapter/adapter.d.ts +8 -1
  9. package/dist/adapter/adapter.d.ts.map +1 -1
  10. package/dist/adapter/adapter.types.d.ts +7 -8
  11. package/dist/adapter/adapter.types.d.ts.map +1 -1
  12. package/dist/client/client.types.d.ts +2 -1
  13. package/dist/client/client.types.d.ts.map +1 -1
  14. package/dist/client/client.utils.d.ts +6 -1
  15. package/dist/client/client.utils.d.ts.map +1 -1
  16. package/dist/index.mjs +1539 -1389
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/infinite/infinite.d.ts.map +1 -1
  19. package/dist/request/request.d.ts +10 -2
  20. package/dist/request/request.d.ts.map +1 -1
  21. package/dist/request/request.types.d.ts +15 -0
  22. package/dist/request/request.types.d.ts.map +1 -1
  23. package/dist/request/request.utils.d.ts +19 -1
  24. package/dist/request/request.utils.d.ts.map +1 -1
  25. package/dist/sdk/sdk.d.ts +1 -0
  26. package/dist/sdk/sdk.d.ts.map +1 -1
  27. package/package.json +1 -1
  28. package/src/adapter/adapter.ts +10 -3
  29. package/src/adapter/adapter.types.ts +7 -5
  30. package/src/client/client.types.ts +2 -1
  31. package/src/client/client.utils.ts +12 -2
  32. package/src/infinite/infinite.ts +2 -1
  33. package/src/request/request.ts +95 -26
  34. package/src/request/request.types.ts +15 -0
  35. package/src/request/request.utils.ts +148 -46
  36. package/src/sdk/sdk.ts +4 -0
@@ -1,4 +1,4 @@
1
- import { getAdapterHeaders, getAdapterPayload } from "adapter";
1
+ import { getAdapterBindings, getAdapterHeaders, getAdapterPayload } from "adapter";
2
2
  import { Client } from "client";
3
3
  import { Plugin } from "plugin";
4
4
 
@@ -140,6 +140,34 @@ describe("Adapter [ Mapping ]", () => {
140
140
  // oxlint-disable-next-line unicorn/no-useless-undefined
141
141
  expect(getAdapterPayload(undefined)).toBeUndefined();
142
142
  });
143
+
144
+ it("should give the custom adapter mapper the raw payload and its config", async () => {
145
+ const mapperClient = new Client({ url: "http://mapping" });
146
+ const config = { prefix: "v1" };
147
+ const received: unknown[] = [];
148
+
149
+ mapperClient.adapter.setPayloadMapperConfig(config).setPayloadMapper((payload, mapperConfig) => {
150
+ // The adapter serves every request of the client, so the payload is not narrowed
151
+ expectTypeOf(payload).toEqualTypeOf<unknown>();
152
+ received.push(payload, mapperConfig);
153
+ return `${config.prefix}:${JSON.stringify(payload)}`;
154
+ });
155
+
156
+ const request = mapperClient
157
+ .createRequest<{ payload: { name: string } }>()({ endpoint: "/mapping", method: "POST" })
158
+ .setPayload({ name: "John" });
159
+
160
+ const { payload } = await getAdapterBindings({
161
+ request,
162
+ requestId: "mapping",
163
+ resolve: () => null,
164
+ onStartTime: () => null,
165
+ internalErrorMapping: (error) => error,
166
+ });
167
+
168
+ expect(received).toEqual([{ name: "John" }, config]);
169
+ expect(payload).toBe('v1:{"name":"John"}');
170
+ });
143
171
  });
144
172
 
145
173
  describe("When the code around the adapter throws", () => {
@@ -29,6 +29,39 @@ describe("Cache [ Modes ]", () => {
29
29
  willRetry: false,
30
30
  };
31
31
 
32
+ describe("client mode (single-user runtimes without a document — auto-detected)", () => {
33
+ afterEach(() => {
34
+ vi.unstubAllGlobals();
35
+ delete (process.versions as Partial<NodeJS.ProcessVersions>).electron;
36
+ });
37
+
38
+ const expectUnscopedResponseCached = () => {
39
+ const client = new Client({ url: "http://test.com" });
40
+ const request = client.createRequest<{ response: any }>()({ endpoint: "/users" });
41
+ const cache = createCache(client);
42
+
43
+ cache.set(request, { ...response, ...details });
44
+
45
+ expect(client.mode).toBe("client");
46
+ expect(cache.get(request.cacheKey)?.data).toStrictEqual({ id: 1 });
47
+ };
48
+
49
+ it("should cache unscoped responses in React Native", () => {
50
+ vi.stubGlobal("document", undefined);
51
+ vi.stubGlobal("navigator", { product: "ReactNative" });
52
+
53
+ expectUnscopedResponseCached();
54
+ });
55
+
56
+ it("should cache unscoped responses in the Electron main process", () => {
57
+ vi.stubGlobal("window", undefined);
58
+ vi.stubGlobal("document", undefined);
59
+ Object.assign(process.versions, { electron: "33.0.0" });
60
+
61
+ expectUnscopedResponseCached();
62
+ });
63
+ });
64
+
32
65
  describe("client mode (browser — auto-detected)", () => {
33
66
  it("should auto-detect client mode in browser environment", () => {
34
67
  const client = new Client({ url: "http://test.com" });
@@ -75,6 +75,30 @@ describe("Client [ Configuration ]", () => {
75
75
  expect(resolveClientMode("auto")).toBe("server");
76
76
  });
77
77
 
78
+ it("should resolve the automatic mode to the client one in React Native", () => {
79
+ // React Native defines window but no document, and marks itself on navigator.product
80
+ removeGlobal("document");
81
+ vi.stubGlobal("navigator", { product: "ReactNative" });
82
+
83
+ expect(new Client({ url: "shared-base-url" }).mode).toBe("client");
84
+ expect(resolveClientMode("auto")).toBe("client");
85
+ expect(resolveClientMode("server")).toBe("server");
86
+ });
87
+
88
+ it("should resolve the automatic mode to the client one in the Electron main process", () => {
89
+ removeGlobal("window");
90
+ removeGlobal("document");
91
+ Object.assign(process.versions, { electron: "33.0.0" });
92
+
93
+ try {
94
+ expect(new Client({ url: "shared-base-url" }).mode).toBe("client");
95
+ expect(resolveClientMode("auto")).toBe("client");
96
+ expect(resolveClientMode("server")).toBe("server");
97
+ } finally {
98
+ delete (process.versions as Partial<NodeJS.ProcessVersions>).electron;
99
+ }
100
+ });
101
+
78
102
  it("should create the client without the window", () => {
79
103
  removeGlobal("window");
80
104
 
@@ -0,0 +1,129 @@
1
+ import { createHttpMockingServer } from "@hyper-fetch/testing";
2
+ import { getErrorMessage } from "adapter";
3
+ import { Client } from "client";
4
+
5
+ const { resetMocks, startServer, stopServer, mockRequest } = createHttpMockingServer();
6
+
7
+ describe("Request [ exec ]", () => {
8
+ const fixture = { id: 1 };
9
+
10
+ let client = new Client({ url: "shared-base-url" });
11
+ let request = client.createRequest<{ response: { id: number } }>()({
12
+ endpoint: "/users",
13
+ });
14
+
15
+ beforeAll(() => {
16
+ startServer();
17
+ });
18
+
19
+ beforeEach(() => {
20
+ client = new Client({ url: "shared-base-url" });
21
+ request = client.createRequest<{ response: { id: number } }>()({
22
+ endpoint: "/users",
23
+ });
24
+ resetMocks();
25
+ });
26
+
27
+ afterAll(() => {
28
+ stopServer();
29
+ });
30
+
31
+ describe("when the request lifecycle runs", () => {
32
+ it("should call the lifecycle callbacks given to exec()", async () => {
33
+ mockRequest(request, { data: fixture });
34
+ const onBeforeSent = vi.fn();
35
+ const onRequestStart = vi.fn();
36
+ const onResponseStart = vi.fn();
37
+ const onResponse = vi.fn();
38
+
39
+ const response = await request.exec({
40
+ onBeforeSent,
41
+ onRequestStart,
42
+ onResponseStart,
43
+ onResponse,
44
+ });
45
+
46
+ expect(response.data).toStrictEqual(fixture);
47
+ expect(onBeforeSent).toHaveBeenCalledOnce();
48
+ expect(onRequestStart).toHaveBeenCalledOnce();
49
+ expect(onResponseStart).toHaveBeenCalledOnce();
50
+ expect(onResponse).toHaveBeenCalledOnce();
51
+ expect(onResponse).toHaveBeenCalledWith(
52
+ expect.objectContaining({
53
+ requestId: onBeforeSent.mock.calls[0][0].requestId,
54
+ response: expect.objectContaining({ data: fixture, success: true }),
55
+ details: expect.objectContaining({ isCanceled: false, retries: 0 }),
56
+ }),
57
+ );
58
+ });
59
+
60
+ it("should fire the $hooks of the request", async () => {
61
+ mockRequest(request, { data: fixture });
62
+ const onBeforeSent = vi.fn();
63
+ const onRequestStart = vi.fn();
64
+ const onResponseStart = vi.fn();
65
+ const onResponse = vi.fn();
66
+ request.$hooks.onBeforeSent(onBeforeSent);
67
+ request.$hooks.onRequestStart(onRequestStart);
68
+ request.$hooks.onResponseStart(onResponseStart);
69
+ request.$hooks.onResponse(onResponse);
70
+
71
+ await request.exec();
72
+
73
+ expect(onBeforeSent).toHaveBeenCalledOnce();
74
+ expect(onRequestStart).toHaveBeenCalledOnce();
75
+ expect(onResponseStart).toHaveBeenCalledOnce();
76
+ expect(onResponse).toHaveBeenCalledOnce();
77
+ });
78
+
79
+ it("should give onResponse the adapter response and resolve with the mapped one", async () => {
80
+ mockRequest(request, { data: fixture });
81
+ const onResponse = vi.fn();
82
+ const mapped = request.setResponseMapper((res) =>
83
+ res.success ? { ...res, data: { id: res.data.id + 1 } } : res,
84
+ );
85
+
86
+ const response = await mapped.exec({ onResponse });
87
+
88
+ expect(response.data).toStrictEqual({ id: 2 });
89
+ expect(onResponse).toHaveBeenCalledWith(
90
+ expect.objectContaining({
91
+ response: expect.objectContaining({ data: { id: 1 } }),
92
+ }),
93
+ );
94
+ });
95
+ });
96
+
97
+ describe("when the call changes the keys", () => {
98
+ it("should send with the abort key given to the call", async () => {
99
+ mockRequest(request, { data: fixture });
100
+
101
+ const response = await request.exec({ abortKey: "custom-abort-key" });
102
+
103
+ expect(response.success).toBeTrue();
104
+ expect(response.data).toStrictEqual(fixture);
105
+ expect(client.requestManager.abortControllers.size).toBe(0);
106
+ });
107
+
108
+ it("should be aborted by the abort key given to the call", async () => {
109
+ let release = () => {};
110
+ mockRequest(request, {
111
+ data: fixture,
112
+ until: new Promise<void>((resolve) => {
113
+ release = resolve;
114
+ }),
115
+ });
116
+
117
+ const executed = request.exec({ abortKey: "custom-abort-key" });
118
+ await new Promise((resolve) => {
119
+ setTimeout(resolve, 0);
120
+ });
121
+ client.requestManager.abortByKey("custom-abort-key");
122
+ release();
123
+ const response = await executed;
124
+
125
+ expect(response.success).toBeFalse();
126
+ expect(response.error).toStrictEqual(getErrorMessage("abort"));
127
+ });
128
+ });
129
+ });
@@ -0,0 +1,243 @@
1
+ import { getErrorMessage } from "adapter";
2
+
3
+ import { createControlledClient, flushPromises, isPending } from "../../utils/controlled-adapter.utils";
4
+
5
+ /**
6
+ * The `signal` of a call only triggers the abort controller HyperFetch keeps for that call, so the call ends the same
7
+ * way `request.abort()` ends it - only without touching the other calls of the same abort key.
8
+ */
9
+ describe("Request [ Signal ]", () => {
10
+ const abortError = getErrorMessage("abort");
11
+
12
+ const setup = (options?: { method?: "GET" | "POST" }) => {
13
+ const { client, calls } = createControlledClient();
14
+ const request = client.createRequest<{
15
+ response: any;
16
+ payload: any;
17
+ error: any;
18
+ }>()({
19
+ endpoint: "/signal",
20
+ method: options?.method ?? "POST",
21
+ });
22
+
23
+ return { client, calls, request };
24
+ };
25
+
26
+ beforeEach(() => {
27
+ vi.useFakeTimers();
28
+ });
29
+
30
+ afterEach(() => {
31
+ vi.useRealTimers();
32
+ });
33
+
34
+ describe.each(["send", "exec"] as const)("When the signal is given to %s", (method) => {
35
+ it("should abort the running call and give the abort error", async () => {
36
+ const { request, calls } = setup();
37
+ const controller = new AbortController();
38
+ const onResponse = vi.fn();
39
+
40
+ const sent = request[method]({ signal: controller.signal, onResponse });
41
+ await flushPromises();
42
+ controller.abort();
43
+ const response = await sent;
44
+
45
+ expect(calls[0].isAborted()).toBeTrue();
46
+ expect(response.success).toBeFalse();
47
+ expect(response.error).toStrictEqual(abortError);
48
+ expect(onResponse).toHaveBeenCalledWith(
49
+ expect.objectContaining({
50
+ details: expect.objectContaining({ isCanceled: true }),
51
+ }),
52
+ );
53
+ });
54
+
55
+ it("should abort only its own call, not the others of the same abort key", async () => {
56
+ const { request, calls } = setup();
57
+ const controller = new AbortController();
58
+
59
+ const aborted = request[method]({ signal: controller.signal });
60
+ const other = request[method]();
61
+ await flushPromises();
62
+ expect(calls).toHaveLength(2);
63
+ controller.abort();
64
+ await flushPromises();
65
+ await calls[1].succeed({ id: 1 });
66
+
67
+ await expect(aborted).resolves.toHaveProperty("error", abortError);
68
+ await expect(other).resolves.toHaveProperty("data", { id: 1 });
69
+ expect(calls[1].isAborted()).toBeFalse();
70
+ });
71
+
72
+ it("should not send anything when the signal is aborted already", async () => {
73
+ const { client, request, calls } = setup();
74
+ const controller = new AbortController();
75
+ controller.abort();
76
+
77
+ const response = await request[method]({ signal: controller.signal });
78
+ await flushPromises();
79
+
80
+ expect(calls).toHaveLength(0);
81
+ expect(response.error).toStrictEqual(abortError);
82
+ // The same status as an abort of a running call
83
+ expect(response.status).toBe(client.adapter.systemErrorStatus);
84
+ expect(client.submitDispatcher.getAllRunningRequests()).toHaveLength(0);
85
+ expect(client.requestManager.abortControllers.size).toBe(0);
86
+ });
87
+
88
+ it("should stop listening to the signal once the call is settled", async () => {
89
+ const { request, calls } = setup();
90
+ const controller = new AbortController();
91
+ const removeListener = vi.spyOn(controller.signal, "removeEventListener");
92
+
93
+ const sent = request[method]({ signal: controller.signal });
94
+ await flushPromises();
95
+ await calls[0].succeed({ id: 1 });
96
+ await sent;
97
+
98
+ expect(removeListener).toHaveBeenCalledWith("abort", expect.any(Function));
99
+ });
100
+
101
+ it("should keep the response when the signal aborts after it", async () => {
102
+ const { client, request, calls } = setup();
103
+ const controller = new AbortController();
104
+
105
+ const sent = request[method]({ signal: controller.signal });
106
+ await flushPromises();
107
+ await calls[0].succeed({ id: 1 });
108
+ const response = await sent;
109
+ controller.abort();
110
+ await flushPromises();
111
+
112
+ expect(response.data).toStrictEqual({ id: 1 });
113
+ expect(client.requestManager.abortControllers.size).toBe(0);
114
+ });
115
+
116
+ it("should still be aborted by request.abort()", async () => {
117
+ const { request } = setup();
118
+ const controller = new AbortController();
119
+
120
+ const sent = request[method]({ signal: controller.signal });
121
+ await flushPromises();
122
+ request.abort();
123
+
124
+ await expect(sent).resolves.toHaveProperty("error", abortError);
125
+ });
126
+ });
127
+
128
+ describe("When the signal is given to send", () => {
129
+ it("should take a queued call out of the queue without sending it", async () => {
130
+ const { client, request, calls } = setup();
131
+ const queued = request.setQueued(true);
132
+ const controller = new AbortController();
133
+ const onRemove = vi.fn();
134
+
135
+ const first = queued.send();
136
+ const second = queued.send({ signal: controller.signal, onRemove });
137
+ await flushPromises();
138
+ expect(calls).toHaveLength(1);
139
+ controller.abort();
140
+ const response = await second;
141
+ await calls[0].succeed({ id: 1 });
142
+
143
+ expect(response.error).toStrictEqual(abortError);
144
+ expect(response.status).toBe(client.adapter.systemErrorStatus);
145
+ expect(onRemove).toHaveBeenCalledOnce();
146
+ await expect(first).resolves.toHaveProperty("data", { id: 1 });
147
+ await flushPromises();
148
+ expect(calls).toHaveLength(1);
149
+ expect(client.submitDispatcher.getQueue(queued.queryKey).requests).toHaveLength(0);
150
+ });
151
+
152
+ it("should not send the retry of a call that waits for it", async () => {
153
+ const { request, calls } = setup();
154
+ const controller = new AbortController();
155
+ const onRetry = vi.fn();
156
+
157
+ const sent = request.setRetry(1).setRetryTime(10_000).send({ signal: controller.signal, onRetry });
158
+ await flushPromises();
159
+ await calls[0].fail({ message: "Failed" });
160
+ expect(onRetry).toHaveBeenCalledOnce();
161
+ controller.abort();
162
+ const response = await sent;
163
+ await vi.advanceTimersByTimeAsync(10_000);
164
+
165
+ expect(response.error).toStrictEqual(abortError);
166
+ expect(calls).toHaveLength(1);
167
+ });
168
+
169
+ it("should only stop waiting for a deduplicated call and keep it for the others", async () => {
170
+ const { request, calls } = setup({ method: "GET" });
171
+ const deduplicated = request.setDeduplicate(true);
172
+ const controller = new AbortController();
173
+
174
+ const first = deduplicated.send();
175
+ const joined = deduplicated.send({ signal: controller.signal });
176
+ await flushPromises();
177
+ expect(calls).toHaveLength(1);
178
+ controller.abort();
179
+
180
+ await expect(joined).resolves.toHaveProperty("error", abortError);
181
+ expect(await isPending(first)).toBeTrue();
182
+ expect(calls[0].isAborted()).toBeFalse();
183
+ await calls[0].succeed({ id: 1 });
184
+ await expect(first).resolves.toHaveProperty("data", { id: 1 });
185
+ });
186
+
187
+ it("should abort the call it joined when the deduplicated call is the one with the signal", async () => {
188
+ const { request, calls } = setup({ method: "GET" });
189
+ const deduplicated = request.setDeduplicate(true);
190
+ const controller = new AbortController();
191
+
192
+ const first = deduplicated.send({ signal: controller.signal });
193
+ const joined = deduplicated.send();
194
+ await flushPromises();
195
+ controller.abort();
196
+
197
+ // The signal belongs to the call which started the request - the joined ones share its outcome
198
+ await expect(first).resolves.toHaveProperty("error", abortError);
199
+ await expect(joined).resolves.toHaveProperty("error", abortError);
200
+ expect(calls[0].isAborted()).toBeTrue();
201
+ });
202
+
203
+ it("should roll back the optimistic change with the abort reason", async () => {
204
+ const { request, calls } = setup();
205
+ const queued = request.setQueued(true);
206
+ const controller = new AbortController();
207
+ const rollback = vi.fn();
208
+
209
+ const first = queued.send();
210
+ const second = queued.send({
211
+ signal: controller.signal,
212
+ optimistic: () => ({ rollback }),
213
+ });
214
+ await flushPromises();
215
+ controller.abort();
216
+ await second;
217
+ await calls[0].succeed();
218
+ await first;
219
+
220
+ expect(rollback).toHaveBeenCalledOnce();
221
+ expect(rollback).toHaveBeenCalledWith(
222
+ expect.objectContaining({
223
+ reason: "abort",
224
+ response: expect.objectContaining({ error: abortError }),
225
+ }),
226
+ );
227
+ });
228
+
229
+ it("should not run the optimistic callback when the signal is aborted already", async () => {
230
+ const { request } = setup();
231
+ const controller = new AbortController();
232
+ const optimisticCallback = vi.fn(() => ({}));
233
+ controller.abort();
234
+
235
+ await request.send({
236
+ signal: controller.signal,
237
+ optimistic: optimisticCallback,
238
+ });
239
+
240
+ expect(optimisticCallback).not.toHaveBeenCalled();
241
+ });
242
+ });
243
+ });