@hyper-fetch/core 9.6.0 → 9.6.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/adapter/adapter.bindings.progress.spec.ts +120 -0
- package/__tests__/features/adapter/adapter.bindings.spec.ts +4 -6
- package/__tests__/features/adapter/adapter.defaults.spec.ts +87 -0
- package/__tests__/features/adapter/adapter.mapping.spec.ts +257 -0
- package/__tests__/features/cache/cache.lazy-storage.clear.spec.ts +145 -0
- package/__tests__/features/cache/cache.lazy-storage.resilience.spec.ts +667 -0
- package/__tests__/features/cache/cache.scoped-events.spec.ts +183 -0
- package/__tests__/features/cache/cache.semantics.spec.ts +785 -0
- package/__tests__/features/cache/cache.structural-sharing.spec.ts +565 -0
- package/__tests__/features/cache/cache.timing.spec.ts +448 -0
- package/__tests__/features/client/client.clear.spec.ts +313 -0
- package/__tests__/features/client/client.configuration.spec.ts +416 -0
- package/__tests__/features/client/client.hydration.round-trip.spec.ts +324 -0
- package/__tests__/features/client/client.interceptor.spec.ts +54 -45
- package/__tests__/features/client/client.interceptors.pipeline.spec.ts +599 -0
- package/__tests__/features/client/client.user-errors.spec.ts +220 -0
- package/__tests__/features/dispatcher/dispatcher.cleanup.spec.ts +534 -0
- package/__tests__/features/dispatcher/dispatcher.control.spec.ts +381 -0
- package/__tests__/features/dispatcher/dispatcher.modes.spec.ts +527 -0
- package/__tests__/features/dispatcher/dispatcher.offline.spec.ts +278 -0
- package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +35 -12
- package/__tests__/features/dispatcher/dispatcher.reentrancy.spec.ts +309 -0
- package/__tests__/features/dispatcher/dispatcher.response-order.spec.ts +241 -0
- package/__tests__/features/dispatcher/dispatcher.retry-flow.spec.ts +554 -0
- package/__tests__/features/dispatcher/dispatcher.retry-removal.spec.ts +196 -0
- package/__tests__/features/dispatcher/dispatcher.retry.spec.ts +4 -3
- package/__tests__/features/http-adapter/http-adapter.e2e.spec.ts +917 -0
- package/__tests__/features/managers/app/app.manager.events.spec.ts +434 -0
- package/__tests__/features/managers/logger/logger.levels.spec.ts +199 -0
- package/__tests__/features/managers/request/request.manager.abort.spec.ts +449 -0
- package/__tests__/features/mocker/mocker.base.spec.ts +22 -3
- package/__tests__/features/mocker/mocker.errors.spec.ts +99 -0
- package/__tests__/features/mocker/mocker.outcomes.spec.ts +308 -0
- package/__tests__/features/plugin/plugin.lifecycle.spec.ts +457 -0
- package/__tests__/features/request/request.async-mapper-removal.spec.ts +138 -0
- package/__tests__/features/request/request.immutability.spec.ts +259 -0
- package/__tests__/features/request/request.inference.spec.ts +269 -0
- package/__tests__/features/request/request.lifecycle.spec.ts +682 -0
- package/__tests__/features/request/request.optimistic-settlement.spec.ts +35 -17
- package/__tests__/features/request/request.values.spec.ts +408 -0
- package/__tests__/features/sdk/sdk.builder.spec.ts +304 -0
- package/__tests__/features/utils/emitter.listeners.spec.ts +202 -0
- package/__tests__/utils/controlled-adapter.utils.ts +119 -0
- package/__tests__/utils/fixtures.utils.ts +193 -0
- package/dist/adapter/adapter.bindings.d.ts.map +1 -1
- package/dist/adapter/adapter.utils.d.ts.map +1 -1
- package/dist/cache/cache.d.ts +12 -1
- package/dist/cache/cache.d.ts.map +1 -1
- package/dist/cache/cache.events.d.ts +20 -6
- package/dist/cache/cache.events.d.ts.map +1 -1
- package/dist/cache/cache.utils.d.ts +1 -0
- package/dist/cache/cache.utils.d.ts.map +1 -1
- package/dist/client/client.d.ts +3 -3
- package/dist/client/client.d.ts.map +1 -1
- package/dist/client/client.utils.d.ts.map +1 -1
- package/dist/dispatcher/dispatcher.d.ts +26 -5
- package/dist/dispatcher/dispatcher.d.ts.map +1 -1
- package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
- package/dist/index.mjs +2127 -1741
- package/dist/index.mjs.map +1 -1
- package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
- package/dist/managers/app/app.manager.d.ts +9 -0
- package/dist/managers/app/app.manager.d.ts.map +1 -1
- package/dist/managers/app/app.manager.utils.d.ts.map +1 -1
- package/dist/managers/logger/logger.manager.d.ts.map +1 -1
- package/dist/managers/request/request.manager.d.ts.map +1 -1
- package/dist/managers/request/request.manager.types.d.ts +2 -0
- package/dist/managers/request/request.manager.types.d.ts.map +1 -1
- package/dist/mocker/mocker.d.ts +1 -1
- package/dist/mocker/mocker.d.ts.map +1 -1
- package/dist/plugin/plugin.d.ts +2 -0
- package/dist/plugin/plugin.d.ts.map +1 -1
- package/dist/request/request.d.ts +1 -1
- package/dist/request/request.d.ts.map +1 -1
- package/dist/request/request.utils.d.ts.map +1 -1
- package/dist/utils/emitter.utils.d.ts.map +1 -1
- package/dist/utils/error.utils.d.ts +17 -0
- package/dist/utils/error.utils.d.ts.map +1 -0
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/adapter/adapter.bindings.ts +46 -18
- package/src/adapter/adapter.utils.ts +47 -7
- package/src/cache/cache.events.ts +24 -8
- package/src/cache/cache.ts +109 -21
- package/src/cache/cache.utils.ts +33 -10
- package/src/client/client.ts +99 -7
- package/src/client/client.utils.ts +10 -4
- package/src/dispatcher/dispatcher.ts +273 -133
- package/src/http-adapter/http-adapter.fetch.ts +15 -3
- package/src/managers/app/app.manager.constants.ts +12 -1
- package/src/managers/app/app.manager.ts +43 -23
- package/src/managers/app/app.manager.utils.ts +8 -4
- package/src/managers/logger/logger.manager.ts +21 -8
- package/src/managers/request/request.manager.ts +7 -1
- package/src/managers/request/request.manager.types.ts +2 -0
- package/src/mocker/mocker.ts +14 -11
- package/src/plugin/plugin.ts +6 -0
- package/src/request/request.ts +31 -22
- package/src/request/request.utils.ts +23 -15
- package/src/utils/emitter.utils.ts +9 -2
- package/src/utils/error.utils.ts +29 -0
- package/src/utils/index.ts +1 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { getAdapterBindings } from "adapter";
|
|
2
|
+
import { Client } from "client";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Progress events must report every new state of a transfer, whatever its size. They used to stop for good once an
|
|
6
|
+
* event with a total of exactly 100 bytes was emitted: the guard compared the size in bytes with 100.
|
|
7
|
+
*/
|
|
8
|
+
describe("Adapter [ Bindings progress ]", () => {
|
|
9
|
+
const requestId = "progress-test";
|
|
10
|
+
|
|
11
|
+
const setup = async () => {
|
|
12
|
+
const client = new Client({ url: "http://localhost:9000" });
|
|
13
|
+
const request = client.createRequest<{ response: string; payload: string }>()({ endpoint: "/progress" });
|
|
14
|
+
const bindings = await getAdapterBindings({
|
|
15
|
+
request,
|
|
16
|
+
requestId,
|
|
17
|
+
resolve: () => null,
|
|
18
|
+
onStartTime: () => null,
|
|
19
|
+
internalErrorMapping: (error) => error,
|
|
20
|
+
});
|
|
21
|
+
const downloads: { loaded: number; total: number; progress: number }[] = [];
|
|
22
|
+
const uploads: { loaded: number; total: number; progress: number }[] = [];
|
|
23
|
+
client.requestManager.events.onDownloadProgressById(requestId, ({ loaded, total, progress }) => {
|
|
24
|
+
downloads.push({ loaded, total, progress });
|
|
25
|
+
});
|
|
26
|
+
client.requestManager.events.onUploadProgressById(requestId, ({ loaded, total, progress }) => {
|
|
27
|
+
uploads.push({ loaded, total, progress });
|
|
28
|
+
});
|
|
29
|
+
return { ...bindings, downloads, uploads };
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
describe("when downloading", () => {
|
|
33
|
+
it("should report a 100 byte body that arrives in two pieces up to 100%", async () => {
|
|
34
|
+
const { onResponseStart, onResponseProgress, onResponseEnd, downloads } = await setup();
|
|
35
|
+
|
|
36
|
+
onResponseStart();
|
|
37
|
+
onResponseProgress({ total: 100, loaded: 50 });
|
|
38
|
+
onResponseProgress({ total: 100, loaded: 100 });
|
|
39
|
+
onResponseEnd();
|
|
40
|
+
|
|
41
|
+
expect(downloads).toEqual([
|
|
42
|
+
{ loaded: 0, total: 1, progress: 0 },
|
|
43
|
+
{ loaded: 50, total: 100, progress: 50 },
|
|
44
|
+
{ loaded: 100, total: 100, progress: 100 },
|
|
45
|
+
]);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("should keep reporting a body without a known size after exactly 100 bytes", async () => {
|
|
49
|
+
const { onResponseStart, onResponseProgress, onResponseEnd, downloads } = await setup();
|
|
50
|
+
|
|
51
|
+
onResponseStart();
|
|
52
|
+
// Without a content length the adapter reports the received size as the total
|
|
53
|
+
onResponseProgress({ total: 100, loaded: 100 });
|
|
54
|
+
onResponseProgress({ total: 120, loaded: 120 });
|
|
55
|
+
onResponseProgress({ total: 150, loaded: 150 });
|
|
56
|
+
onResponseEnd();
|
|
57
|
+
|
|
58
|
+
expect(downloads.map(({ loaded }) => loaded)).toEqual([0, 100, 120, 150]);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it.each([1, 50, 99, 100, 101, 1000])("should report the same events for a %i byte body", async (size) => {
|
|
62
|
+
const { onResponseStart, onResponseProgress, onResponseEnd, downloads } = await setup();
|
|
63
|
+
|
|
64
|
+
onResponseStart();
|
|
65
|
+
onResponseProgress({ total: size, loaded: Math.floor(size / 2) });
|
|
66
|
+
onResponseProgress({ total: size, loaded: size });
|
|
67
|
+
onResponseEnd();
|
|
68
|
+
|
|
69
|
+
expect(downloads.at(-1)).toEqual({ loaded: size, total: size, progress: 100 });
|
|
70
|
+
// 1 byte bodies have no half, so the middle event repeats the start
|
|
71
|
+
expect(downloads).toHaveLength(size === 1 ? 2 : 3);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it("should not report the same progress twice in a row", async () => {
|
|
75
|
+
const { onResponseStart, onResponseProgress, onResponseEnd, downloads } = await setup();
|
|
76
|
+
|
|
77
|
+
onResponseStart();
|
|
78
|
+
onResponseProgress({ total: 10, loaded: 5 });
|
|
79
|
+
onResponseProgress({ total: 10, loaded: 5 });
|
|
80
|
+
onResponseProgress({ total: 10, loaded: 10 });
|
|
81
|
+
onResponseEnd();
|
|
82
|
+
onResponseEnd();
|
|
83
|
+
|
|
84
|
+
expect(downloads.map(({ loaded }) => loaded)).toEqual([0, 5, 10]);
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
describe("when uploading", () => {
|
|
89
|
+
it.each([99, 100, 101])("should report a %i byte payload up to 100%", async (size) => {
|
|
90
|
+
const { onRequestStart, onRequestProgress, onRequestEnd, uploads } = await setup();
|
|
91
|
+
|
|
92
|
+
onRequestStart({ total: size, loaded: 0 });
|
|
93
|
+
onRequestProgress({ total: size, loaded: Math.floor(size / 2) });
|
|
94
|
+
onRequestProgress({ total: size, loaded: size });
|
|
95
|
+
onRequestEnd();
|
|
96
|
+
|
|
97
|
+
expect(uploads).toEqual([
|
|
98
|
+
{ loaded: 0, total: size, progress: 0 },
|
|
99
|
+
{ loaded: Math.floor(size / 2), total: size, progress: Math.round((Math.floor(size / 2) * 100) / size) },
|
|
100
|
+
{ loaded: size, total: size, progress: 100 },
|
|
101
|
+
]);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("should keep reporting after a 100 byte upload event", async () => {
|
|
105
|
+
const { onRequestStart, onRequestProgress, onRequestEnd, uploads } = await setup();
|
|
106
|
+
|
|
107
|
+
onRequestStart();
|
|
108
|
+
onRequestProgress({ total: 100, loaded: 100 });
|
|
109
|
+
onRequestProgress({ total: 300, loaded: 200 });
|
|
110
|
+
onRequestEnd();
|
|
111
|
+
|
|
112
|
+
expect(uploads.map(({ loaded, total }) => [loaded, total])).toEqual([
|
|
113
|
+
[0, 1],
|
|
114
|
+
[100, 100],
|
|
115
|
+
[200, 300],
|
|
116
|
+
[300, 300],
|
|
117
|
+
]);
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
});
|
|
@@ -974,7 +974,7 @@ describe("Adapter [ Bindings ]", () => {
|
|
|
974
974
|
});
|
|
975
975
|
|
|
976
976
|
describe("when handling progress updates", () => {
|
|
977
|
-
it("should skip upload progress event
|
|
977
|
+
it("should skip an upload progress event identical to the previous one", async () => {
|
|
978
978
|
const { onRequestProgress } = await getAdapterBindings({
|
|
979
979
|
request,
|
|
980
980
|
requestId,
|
|
@@ -986,11 +986,10 @@ describe("Adapter [ Bindings ]", () => {
|
|
|
986
986
|
const spy = vi.fn();
|
|
987
987
|
const unmount = client.requestManager.events.onUploadProgressByQueue(request.queryKey, spy);
|
|
988
988
|
|
|
989
|
-
// First call to set previousRequestTotal to 100
|
|
990
989
|
onRequestProgress({ total: 100, loaded: 100 });
|
|
991
990
|
expect(spy).toHaveBeenCalledTimes(1);
|
|
992
991
|
|
|
993
|
-
//
|
|
992
|
+
// The same progress again is not emitted
|
|
994
993
|
spy.mockClear();
|
|
995
994
|
onRequestProgress({ total: 100, loaded: 100 });
|
|
996
995
|
expect(spy).not.toHaveBeenCalled();
|
|
@@ -998,7 +997,7 @@ describe("Adapter [ Bindings ]", () => {
|
|
|
998
997
|
unmount();
|
|
999
998
|
});
|
|
1000
999
|
|
|
1001
|
-
it("should skip download progress event
|
|
1000
|
+
it("should skip a download progress event identical to the previous one", async () => {
|
|
1002
1001
|
const { onResponseProgress } = await getAdapterBindings({
|
|
1003
1002
|
request,
|
|
1004
1003
|
requestId,
|
|
@@ -1010,11 +1009,10 @@ describe("Adapter [ Bindings ]", () => {
|
|
|
1010
1009
|
const spy = vi.fn();
|
|
1011
1010
|
const unmount = client.requestManager.events.onDownloadProgressByQueue(request.queryKey, spy);
|
|
1012
1011
|
|
|
1013
|
-
// First call to set previousResponseTotal to 100
|
|
1014
1012
|
onResponseProgress({ total: 100, loaded: 100 });
|
|
1015
1013
|
expect(spy).toHaveBeenCalledTimes(1);
|
|
1016
1014
|
|
|
1017
|
-
//
|
|
1015
|
+
// The same progress again is not emitted
|
|
1018
1016
|
spy.mockClear();
|
|
1019
1017
|
onResponseProgress({ total: 100, loaded: 100 });
|
|
1020
1018
|
expect(spy).not.toHaveBeenCalled();
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { createHttpMockingServer } from "@hyper-fetch/testing";
|
|
2
|
+
import { getAdapterBindings, getErrorMessage } from "adapter";
|
|
3
|
+
import { Client } from "client";
|
|
4
|
+
|
|
5
|
+
const { resetMocks, startServer, stopServer, mockRequest } = createHttpMockingServer();
|
|
6
|
+
|
|
7
|
+
/** `adapter.setAdapterDefaults()` sets adapter options for every request; a request's own options win. */
|
|
8
|
+
describe("Adapter [ Defaults ]", () => {
|
|
9
|
+
beforeAll(() => {
|
|
10
|
+
startServer();
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
beforeEach(() => {
|
|
14
|
+
resetMocks();
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
afterAll(() => {
|
|
18
|
+
stopServer();
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const getOptions = async (client: Client, options?: Record<string, unknown>) => {
|
|
22
|
+
const request = client.createRequest()({ endpoint: "/defaults", ...(options && { options }) });
|
|
23
|
+
const { adapterOptions } = await getAdapterBindings({
|
|
24
|
+
request,
|
|
25
|
+
requestId: "defaults",
|
|
26
|
+
resolve: () => null,
|
|
27
|
+
onStartTime: () => null,
|
|
28
|
+
internalErrorMapping: (error) => error,
|
|
29
|
+
});
|
|
30
|
+
return adapterOptions;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
it("should apply the defaults to a request without options", async () => {
|
|
34
|
+
const client = new Client({ url: "http://localhost:9000" });
|
|
35
|
+
client.adapter.setAdapterDefaults(() => ({ timeout: 1234 }));
|
|
36
|
+
|
|
37
|
+
expect(await getOptions(client)).toEqual({ timeout: 1234 });
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it("should let the request options override the defaults", async () => {
|
|
41
|
+
const client = new Client({ url: "http://localhost:9000" });
|
|
42
|
+
client.adapter.setAdapterDefaults(() => ({ timeout: 1234, credentials: "include" }));
|
|
43
|
+
|
|
44
|
+
expect(await getOptions(client, { timeout: 99 })).toEqual({ timeout: 99, credentials: "include" });
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it("should pass the request to the defaults callback", async () => {
|
|
48
|
+
const client = new Client({ url: "http://localhost:9000" });
|
|
49
|
+
const callback = vi.fn(() => ({ timeout: 1 }));
|
|
50
|
+
client.adapter.setAdapterDefaults(callback);
|
|
51
|
+
|
|
52
|
+
await getOptions(client);
|
|
53
|
+
|
|
54
|
+
expect(callback).toHaveBeenCalledWith(expect.objectContaining({ endpoint: "/defaults" }));
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it("should keep the request options untouched without defaults", async () => {
|
|
58
|
+
const client = new Client({ url: "http://localhost:9000" });
|
|
59
|
+
|
|
60
|
+
expect(await getOptions(client)).toBeUndefined();
|
|
61
|
+
expect(await getOptions(client, { timeout: 5 })).toEqual({ timeout: 5 });
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it("should make the fetch adapter use a default timeout", async () => {
|
|
65
|
+
const client = new Client({ url: "http://localhost:9000" });
|
|
66
|
+
client.adapter.setAdapterDefaults(() => ({ timeout: 20 }));
|
|
67
|
+
const request = client.createRequest<{ response: { ok: boolean } }>()({ endpoint: "/slow" });
|
|
68
|
+
mockRequest(request, { data: { ok: true }, delay: 300 });
|
|
69
|
+
|
|
70
|
+
const response = await request.send();
|
|
71
|
+
|
|
72
|
+
expect(response.error).toEqual(getErrorMessage("timeout"));
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it("should still succeed when the request overrides a short default timeout", async () => {
|
|
76
|
+
const client = new Client({ url: "http://localhost:9000" });
|
|
77
|
+
client.adapter.setAdapterDefaults(() => ({ timeout: 20 }));
|
|
78
|
+
const request = client
|
|
79
|
+
.createRequest<{ response: { ok: boolean } }>()({ endpoint: "/slow" })
|
|
80
|
+
.setOptions({ timeout: 5000 });
|
|
81
|
+
mockRequest(request, { data: { ok: true }, delay: 100 });
|
|
82
|
+
|
|
83
|
+
const response = await request.send();
|
|
84
|
+
|
|
85
|
+
expect(response.data).toEqual({ ok: true });
|
|
86
|
+
});
|
|
87
|
+
});
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { getAdapterHeaders, getAdapterPayload } from "adapter";
|
|
2
|
+
import { Client } from "client";
|
|
3
|
+
import { Plugin } from "plugin";
|
|
4
|
+
|
|
5
|
+
import { createControlledClient, flushPromises } from "../../utils/controlled-adapter.utils";
|
|
6
|
+
|
|
7
|
+
describe("Adapter [ Mapping ]", () => {
|
|
8
|
+
const client = new Client({ url: "http://mapping" });
|
|
9
|
+
const createRequest = () =>
|
|
10
|
+
client.createRequest<{ payload: any; response: any }>()({ endpoint: "/mapping", method: "POST" });
|
|
11
|
+
|
|
12
|
+
describe("When mapping the headers", () => {
|
|
13
|
+
it("should give no headers for a request without a payload", () => {
|
|
14
|
+
expect(getAdapterHeaders(createRequest())).toEqual({});
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it.each([
|
|
18
|
+
["an object", { name: "John" }],
|
|
19
|
+
["an array", [1, 2, 3]],
|
|
20
|
+
["an empty object", {}],
|
|
21
|
+
])("should add the JSON content type for %s", (_, payload) => {
|
|
22
|
+
expect(getAdapterHeaders(createRequest().setPayload(payload))).toEqual({ "Content-Type": "application/json" });
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it.each([
|
|
26
|
+
["a string", "text"],
|
|
27
|
+
["a number", 5],
|
|
28
|
+
["a boolean", true],
|
|
29
|
+
])("should not add the content type for %s", (_, payload) => {
|
|
30
|
+
expect(getAdapterHeaders(createRequest().setPayload(payload))).toEqual({});
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it.each([
|
|
34
|
+
["FormData", () => new FormData()],
|
|
35
|
+
["Blob", () => new Blob(["content"], { type: "text/plain" })],
|
|
36
|
+
["ArrayBuffer", () => new ArrayBuffer(4)],
|
|
37
|
+
["Uint8Array", () => new Uint8Array([1, 2])],
|
|
38
|
+
["DataView", () => new DataView(new ArrayBuffer(4))],
|
|
39
|
+
["URLSearchParams", () => new URLSearchParams({ a: "1" })],
|
|
40
|
+
["ReadableStream", () => new ReadableStream()],
|
|
41
|
+
])("should leave the content type of %s to the transport", (_, createPayload) => {
|
|
42
|
+
expect(getAdapterHeaders(createRequest().setPayload(createPayload()))).toEqual({});
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it("should keep the headers of the request", () => {
|
|
46
|
+
const request = createRequest().setHeaders({ Authorization: "Bearer token", "X-Custom": "1" });
|
|
47
|
+
|
|
48
|
+
expect(getAdapterHeaders(request)).toEqual({ Authorization: "Bearer token", "X-Custom": "1" });
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("should read the Headers instance", () => {
|
|
52
|
+
const request = createRequest()
|
|
53
|
+
.setHeaders(new Headers({ Authorization: "Bearer token" }))
|
|
54
|
+
.setPayload({ a: 1 });
|
|
55
|
+
|
|
56
|
+
expect(getAdapterHeaders(request)).toEqual({
|
|
57
|
+
authorization: "Bearer token",
|
|
58
|
+
"Content-Type": "application/json",
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it("should read the list of pairs", () => {
|
|
63
|
+
const request = createRequest().setHeaders([
|
|
64
|
+
["Authorization", "Bearer token"],
|
|
65
|
+
["X-Custom", "1"],
|
|
66
|
+
]);
|
|
67
|
+
|
|
68
|
+
expect(getAdapterHeaders(request)).toEqual({ Authorization: "Bearer token", "X-Custom": "1" });
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it.each(["Content-Type", "content-type", "CONTENT-TYPE", "Content-type"])(
|
|
72
|
+
"should not add the default content type next to the %s header",
|
|
73
|
+
(name) => {
|
|
74
|
+
const request = createRequest()
|
|
75
|
+
.setHeaders({ [name]: "text/plain" })
|
|
76
|
+
.setPayload({ a: 1 });
|
|
77
|
+
|
|
78
|
+
expect(getAdapterHeaders(request)).toEqual({ [name]: "text/plain" });
|
|
79
|
+
},
|
|
80
|
+
);
|
|
81
|
+
|
|
82
|
+
it("should drop the headers with empty values", () => {
|
|
83
|
+
const headers = { "X-Null": null, "X-Undefined": undefined, "X-Empty": "", "X-Kept": "1" };
|
|
84
|
+
const request = createRequest().setHeaders(headers as unknown as HeadersInit);
|
|
85
|
+
|
|
86
|
+
expect(getAdapterHeaders(request)).toEqual({ "X-Empty": "", "X-Kept": "1" });
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("should let an empty content type remove the default one", () => {
|
|
90
|
+
const request = createRequest()
|
|
91
|
+
.setHeaders({ "Content-Type": undefined } as unknown as HeadersInit)
|
|
92
|
+
.setPayload({ a: 1 });
|
|
93
|
+
|
|
94
|
+
expect(getAdapterHeaders(request)).toEqual({});
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("should not change the headers of the request", () => {
|
|
98
|
+
const headers = { "X-Custom": "1" };
|
|
99
|
+
const request = createRequest().setHeaders(headers).setPayload({ a: 1 });
|
|
100
|
+
|
|
101
|
+
getAdapterHeaders(request);
|
|
102
|
+
|
|
103
|
+
expect(headers).toEqual({ "X-Custom": "1" });
|
|
104
|
+
expect(request.headers).toBe(headers);
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
describe("When mapping the payload", () => {
|
|
109
|
+
it.each([
|
|
110
|
+
["an object", { name: "John" }, '{"name":"John"}'],
|
|
111
|
+
["an array", [1, 2], "[1,2]"],
|
|
112
|
+
["a string", "text", '"text"'],
|
|
113
|
+
["a number", 0, "0"],
|
|
114
|
+
["a boolean", false, "false"],
|
|
115
|
+
["null", null, "null"],
|
|
116
|
+
["a date", new Date(0), '"1970-01-01T00:00:00.000Z"'],
|
|
117
|
+
])("should stringify %s", (_, payload, expected) => {
|
|
118
|
+
expect(getAdapterPayload(payload)).toBe(expected);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it.each([
|
|
122
|
+
["FormData", () => new FormData()],
|
|
123
|
+
["Blob", () => new Blob(["content"])],
|
|
124
|
+
["ArrayBuffer", () => new ArrayBuffer(4)],
|
|
125
|
+
["Uint8Array", () => new Uint8Array([1, 2])],
|
|
126
|
+
["DataView", () => new DataView(new ArrayBuffer(4))],
|
|
127
|
+
["URLSearchParams", () => new URLSearchParams({ a: "1" })],
|
|
128
|
+
["ReadableStream", () => new ReadableStream()],
|
|
129
|
+
])("should pass %s through untouched", (_, createPayload) => {
|
|
130
|
+
const payload = createPayload();
|
|
131
|
+
|
|
132
|
+
expect(getAdapterPayload(payload)).toBe(payload);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it("should give nothing for a payload which can't be stringified", () => {
|
|
136
|
+
const circular: Record<string, unknown> = {};
|
|
137
|
+
circular.self = circular;
|
|
138
|
+
|
|
139
|
+
expect(getAdapterPayload(circular)).toBe("");
|
|
140
|
+
// oxlint-disable-next-line unicorn/no-useless-undefined
|
|
141
|
+
expect(getAdapterPayload(undefined)).toBeUndefined();
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
describe("When the code around the adapter throws", () => {
|
|
146
|
+
beforeEach(() => {
|
|
147
|
+
vi.useFakeTimers();
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
afterEach(() => {
|
|
151
|
+
vi.useRealTimers();
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
const setup = () => {
|
|
155
|
+
const controlled = createControlledClient();
|
|
156
|
+
const request = controlled.client.createRequest<{ response: any; error: any }>()({
|
|
157
|
+
endpoint: "/throwing",
|
|
158
|
+
method: "POST",
|
|
159
|
+
});
|
|
160
|
+
return { ...controlled, request };
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
const answer = async (
|
|
164
|
+
calls: ReturnType<typeof setup>["calls"],
|
|
165
|
+
sent: Promise<{ success: boolean; error: any; data: any }>,
|
|
166
|
+
outcome: "succeed" | "fail",
|
|
167
|
+
) => {
|
|
168
|
+
await flushPromises();
|
|
169
|
+
await calls[0][outcome]();
|
|
170
|
+
return sent;
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
it.each([
|
|
174
|
+
["onResponse", "succeed"],
|
|
175
|
+
["onSuccess", "succeed"],
|
|
176
|
+
["onResponse", "fail"],
|
|
177
|
+
["onError", "fail"],
|
|
178
|
+
] as const)("should give an error response when the %s interceptor throws", async (interceptor, outcome) => {
|
|
179
|
+
const { client: controlledClient, calls, request } = setup();
|
|
180
|
+
controlledClient[interceptor](() => {
|
|
181
|
+
throw new Error("Broken interceptor");
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
const response = await answer(calls, request.send(), outcome);
|
|
185
|
+
|
|
186
|
+
expect(response.success).toBe(false);
|
|
187
|
+
expect(response.data).toBeNull();
|
|
188
|
+
expect(response.error.message).toBe("Broken interceptor");
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
it.each(["succeed", "fail"] as const)(
|
|
192
|
+
"should settle the request when a plugin throws after the request did %s",
|
|
193
|
+
async (outcome) => {
|
|
194
|
+
const { client: controlledClient, calls, request } = setup();
|
|
195
|
+
controlledClient.addPlugin(
|
|
196
|
+
new Plugin({ name: "broken" }).onRequestFinished(() => {
|
|
197
|
+
throw new Error("Broken plugin");
|
|
198
|
+
}),
|
|
199
|
+
);
|
|
200
|
+
|
|
201
|
+
const response = await answer(calls, request.send(), outcome);
|
|
202
|
+
|
|
203
|
+
expect(response).toBeDefined();
|
|
204
|
+
expect(controlledClient.submitDispatcher.getQueue(request.queryKey).requests).toHaveLength(0);
|
|
205
|
+
},
|
|
206
|
+
);
|
|
207
|
+
|
|
208
|
+
it("should give an error response when the request interceptor throws", async () => {
|
|
209
|
+
const { client: controlledClient, calls, request } = setup();
|
|
210
|
+
controlledClient.onRequest(() => {
|
|
211
|
+
throw new Error("Broken interceptor");
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
const response = await request.send();
|
|
215
|
+
|
|
216
|
+
expect(response.success).toBe(false);
|
|
217
|
+
expect(response.error.message).toBe("Broken interceptor");
|
|
218
|
+
expect(calls).toHaveLength(0);
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
it("should give an error response when the fetcher throws", async () => {
|
|
222
|
+
const { client: controlledClient, request } = setup();
|
|
223
|
+
controlledClient.adapter.setFetcher(() => {
|
|
224
|
+
throw new Error("Broken fetcher");
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
const response = await request.send();
|
|
228
|
+
|
|
229
|
+
expect(response.success).toBe(false);
|
|
230
|
+
expect(response.status).toBe(0);
|
|
231
|
+
expect(response.error.message).toBe("Broken fetcher");
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it("should give an error response when the adapter has no fetcher", async () => {
|
|
235
|
+
const { client: controlledClient, request } = setup();
|
|
236
|
+
controlledClient.adapter.unstable_fetcher = undefined as never;
|
|
237
|
+
|
|
238
|
+
const response = await request.send();
|
|
239
|
+
|
|
240
|
+
expect(response.success).toBe(false);
|
|
241
|
+
expect(response.error.message).toBe("Request processing error");
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
it("should leave the dispatcher clean after the failures", async () => {
|
|
245
|
+
const { client: controlledClient, calls, request } = setup();
|
|
246
|
+
controlledClient.onResponse(() => {
|
|
247
|
+
throw new Error("Broken interceptor");
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
await answer(calls, request.send(), "succeed");
|
|
251
|
+
|
|
252
|
+
expect(controlledClient.submitDispatcher.getQueue(request.queryKey).requests).toHaveLength(0);
|
|
253
|
+
expect(controlledClient.submitDispatcher.getAllRunningRequests()).toHaveLength(0);
|
|
254
|
+
expect(controlledClient.requestManager.abortControllers.size).toBe(0);
|
|
255
|
+
});
|
|
256
|
+
});
|
|
257
|
+
});
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import type { CacheAsyncStorageType, CacheValueType } from "cache";
|
|
2
|
+
import { Cache } from "cache";
|
|
3
|
+
import { Client } from "client";
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
createCacheResponse,
|
|
7
|
+
createCacheValue,
|
|
8
|
+
createLazyStorage,
|
|
9
|
+
flushPromises,
|
|
10
|
+
getUnhandledRejections,
|
|
11
|
+
} from "../../utils/fixtures.utils";
|
|
12
|
+
|
|
13
|
+
const version = "test-version";
|
|
14
|
+
|
|
15
|
+
const createLazyClient = (lazyStorage: CacheAsyncStorageType) => {
|
|
16
|
+
const client = new Client({ url: "shared-base-url", cache: () => new Cache({ lazyStorage, version }) });
|
|
17
|
+
const request = client.createRequest<{ response: { owner: string } }>()({ endpoint: "/profile" });
|
|
18
|
+
|
|
19
|
+
return { client, request };
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Clearing the cache is how an application forgets its data, for example on logout. Data left in the lazy
|
|
24
|
+
* (persistent) storage would be loaded back by the next read - for the next user.
|
|
25
|
+
*/
|
|
26
|
+
describe("Cache [ Lazy Storage Clear ]", () => {
|
|
27
|
+
describe("When the cache is cleared", () => {
|
|
28
|
+
it("should remove every element from the lazy storage", async () => {
|
|
29
|
+
const { storage, source } = createLazyStorage();
|
|
30
|
+
const { client, request } = createLazyClient(storage);
|
|
31
|
+
client.cache.set(request, createCacheResponse({ owner: "first user" }));
|
|
32
|
+
client.cache.set(request.setScope("other"), createCacheResponse({ owner: "second user" }));
|
|
33
|
+
await flushPromises();
|
|
34
|
+
expect(source.size).toBe(2);
|
|
35
|
+
|
|
36
|
+
await client.cache.clear();
|
|
37
|
+
|
|
38
|
+
expect(source.size).toBe(0);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it("should not load the cleared data back on the next read", async () => {
|
|
42
|
+
const { storage } = createLazyStorage();
|
|
43
|
+
const { client, request } = createLazyClient(storage);
|
|
44
|
+
const received = vi.fn();
|
|
45
|
+
client.cache.set(request, createCacheResponse({ owner: "first user" }));
|
|
46
|
+
await flushPromises();
|
|
47
|
+
|
|
48
|
+
await client.cache.clear();
|
|
49
|
+
client.cache.events.onDataByKey(request.cacheKey, received);
|
|
50
|
+
const value = client.cache.get(request.cacheKey);
|
|
51
|
+
await flushPromises();
|
|
52
|
+
|
|
53
|
+
expect(value).toBeUndefined();
|
|
54
|
+
expect(received).not.toHaveBeenCalled();
|
|
55
|
+
expect(await client.cache.getLazyResource(request.cacheKey)).toBeUndefined();
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it("should remove the elements that were only in the lazy storage", async () => {
|
|
59
|
+
const source = new Map<string, CacheValueType>([
|
|
60
|
+
["persisted-a", createCacheValue({ cacheKey: "persisted-a", version, data: { owner: "a" } })],
|
|
61
|
+
["persisted-b", createCacheValue({ cacheKey: "persisted-b", version, data: { owner: "b" } })],
|
|
62
|
+
]);
|
|
63
|
+
const { storage } = createLazyStorage(source);
|
|
64
|
+
const { client } = createLazyClient(storage);
|
|
65
|
+
|
|
66
|
+
await client.cache.clear();
|
|
67
|
+
|
|
68
|
+
expect([...source.keys()]).toStrictEqual([]);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("should accept a lazy storage that returns its keys as an iterator", async () => {
|
|
72
|
+
const { storage, source, spies } = createLazyStorage();
|
|
73
|
+
spies.keys.mockImplementation((async () => source.keys()) as never);
|
|
74
|
+
const { client, request } = createLazyClient(storage);
|
|
75
|
+
client.cache.set(request, createCacheResponse({ owner: "first user" }));
|
|
76
|
+
await flushPromises();
|
|
77
|
+
|
|
78
|
+
await client.cache.clear();
|
|
79
|
+
|
|
80
|
+
expect(source.size).toBe(0);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it("should clear the memory also when there is no lazy storage", async () => {
|
|
84
|
+
const client = new Client({ url: "shared-base-url" });
|
|
85
|
+
const request = client.createRequest<{ response: { owner: string } }>()({ endpoint: "/profile" });
|
|
86
|
+
client.cache.set(request, createCacheResponse({ owner: "first user" }));
|
|
87
|
+
|
|
88
|
+
await client.cache.clear();
|
|
89
|
+
|
|
90
|
+
expect(client.cache.get(request.cacheKey)).toBeUndefined();
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
describe("When the client is cleared", () => {
|
|
95
|
+
it("should remove the data from the lazy storage", async () => {
|
|
96
|
+
const { storage, source } = createLazyStorage();
|
|
97
|
+
const { client, request } = createLazyClient(storage);
|
|
98
|
+
client.cache.set(request, createCacheResponse({ owner: "first user" }));
|
|
99
|
+
await flushPromises();
|
|
100
|
+
|
|
101
|
+
client.clear();
|
|
102
|
+
await flushPromises();
|
|
103
|
+
|
|
104
|
+
expect(source.size).toBe(0);
|
|
105
|
+
expect(await client.cache.getLazyResource(request.cacheKey)).toBeUndefined();
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
describe("When the lazy storage fails", () => {
|
|
110
|
+
it.each([
|
|
111
|
+
["reading the keys", "keys"],
|
|
112
|
+
["deleting an element", "delete"],
|
|
113
|
+
] as const)("should still clear the memory when %s rejects", async (_name, method) => {
|
|
114
|
+
const { storage, spies } = createLazyStorage();
|
|
115
|
+
const { client, request } = createLazyClient(storage);
|
|
116
|
+
client.cache.set(request, createCacheResponse({ owner: "first user" }));
|
|
117
|
+
await flushPromises();
|
|
118
|
+
spies[method].mockRejectedValue(new Error("Storage is not available"));
|
|
119
|
+
|
|
120
|
+
const rejections = await getUnhandledRejections(() => client.cache.clear());
|
|
121
|
+
|
|
122
|
+
expect(rejections).toStrictEqual([]);
|
|
123
|
+
expect(client.cache.get(request.cacheKey)).toBeUndefined();
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it("should remove the other elements when deleting one of them rejects", async () => {
|
|
127
|
+
const source = new Map<string, CacheValueType>([
|
|
128
|
+
["broken", createCacheValue({ cacheKey: "broken", version, data: { owner: "a" } })],
|
|
129
|
+
["fine", createCacheValue({ cacheKey: "fine", version, data: { owner: "b" } })],
|
|
130
|
+
]);
|
|
131
|
+
const { storage, spies } = createLazyStorage(source);
|
|
132
|
+
spies.delete.mockImplementation(async (key: string) => {
|
|
133
|
+
if (key === "broken") {
|
|
134
|
+
throw new Error("Storage is not available");
|
|
135
|
+
}
|
|
136
|
+
source.delete(key);
|
|
137
|
+
});
|
|
138
|
+
const { client } = createLazyClient(storage);
|
|
139
|
+
|
|
140
|
+
await client.cache.clear();
|
|
141
|
+
|
|
142
|
+
expect([...source.keys()]).toStrictEqual(["broken"]);
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
});
|