@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.
Files changed (103) hide show
  1. package/__tests__/features/adapter/adapter.bindings.progress.spec.ts +120 -0
  2. package/__tests__/features/adapter/adapter.bindings.spec.ts +4 -6
  3. package/__tests__/features/adapter/adapter.defaults.spec.ts +87 -0
  4. package/__tests__/features/adapter/adapter.mapping.spec.ts +257 -0
  5. package/__tests__/features/cache/cache.lazy-storage.clear.spec.ts +145 -0
  6. package/__tests__/features/cache/cache.lazy-storage.resilience.spec.ts +667 -0
  7. package/__tests__/features/cache/cache.scoped-events.spec.ts +183 -0
  8. package/__tests__/features/cache/cache.semantics.spec.ts +785 -0
  9. package/__tests__/features/cache/cache.structural-sharing.spec.ts +565 -0
  10. package/__tests__/features/cache/cache.timing.spec.ts +448 -0
  11. package/__tests__/features/client/client.clear.spec.ts +313 -0
  12. package/__tests__/features/client/client.configuration.spec.ts +416 -0
  13. package/__tests__/features/client/client.hydration.round-trip.spec.ts +324 -0
  14. package/__tests__/features/client/client.interceptor.spec.ts +54 -45
  15. package/__tests__/features/client/client.interceptors.pipeline.spec.ts +599 -0
  16. package/__tests__/features/client/client.user-errors.spec.ts +220 -0
  17. package/__tests__/features/dispatcher/dispatcher.cleanup.spec.ts +534 -0
  18. package/__tests__/features/dispatcher/dispatcher.control.spec.ts +381 -0
  19. package/__tests__/features/dispatcher/dispatcher.modes.spec.ts +527 -0
  20. package/__tests__/features/dispatcher/dispatcher.offline.spec.ts +278 -0
  21. package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +35 -12
  22. package/__tests__/features/dispatcher/dispatcher.reentrancy.spec.ts +309 -0
  23. package/__tests__/features/dispatcher/dispatcher.response-order.spec.ts +241 -0
  24. package/__tests__/features/dispatcher/dispatcher.retry-flow.spec.ts +554 -0
  25. package/__tests__/features/dispatcher/dispatcher.retry-removal.spec.ts +196 -0
  26. package/__tests__/features/dispatcher/dispatcher.retry.spec.ts +4 -3
  27. package/__tests__/features/http-adapter/http-adapter.e2e.spec.ts +917 -0
  28. package/__tests__/features/managers/app/app.manager.events.spec.ts +434 -0
  29. package/__tests__/features/managers/logger/logger.levels.spec.ts +199 -0
  30. package/__tests__/features/managers/request/request.manager.abort.spec.ts +449 -0
  31. package/__tests__/features/mocker/mocker.base.spec.ts +22 -3
  32. package/__tests__/features/mocker/mocker.errors.spec.ts +99 -0
  33. package/__tests__/features/mocker/mocker.outcomes.spec.ts +308 -0
  34. package/__tests__/features/plugin/plugin.lifecycle.spec.ts +457 -0
  35. package/__tests__/features/request/request.async-mapper-removal.spec.ts +138 -0
  36. package/__tests__/features/request/request.immutability.spec.ts +259 -0
  37. package/__tests__/features/request/request.inference.spec.ts +269 -0
  38. package/__tests__/features/request/request.lifecycle.spec.ts +682 -0
  39. package/__tests__/features/request/request.optimistic-settlement.spec.ts +35 -17
  40. package/__tests__/features/request/request.values.spec.ts +408 -0
  41. package/__tests__/features/sdk/sdk.builder.spec.ts +304 -0
  42. package/__tests__/features/utils/emitter.listeners.spec.ts +202 -0
  43. package/__tests__/utils/controlled-adapter.utils.ts +119 -0
  44. package/__tests__/utils/fixtures.utils.ts +193 -0
  45. package/dist/adapter/adapter.bindings.d.ts.map +1 -1
  46. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  47. package/dist/cache/cache.d.ts +12 -1
  48. package/dist/cache/cache.d.ts.map +1 -1
  49. package/dist/cache/cache.events.d.ts +20 -6
  50. package/dist/cache/cache.events.d.ts.map +1 -1
  51. package/dist/cache/cache.utils.d.ts +1 -0
  52. package/dist/cache/cache.utils.d.ts.map +1 -1
  53. package/dist/client/client.d.ts +3 -3
  54. package/dist/client/client.d.ts.map +1 -1
  55. package/dist/client/client.utils.d.ts.map +1 -1
  56. package/dist/dispatcher/dispatcher.d.ts +26 -5
  57. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  58. package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
  59. package/dist/index.mjs +2127 -1741
  60. package/dist/index.mjs.map +1 -1
  61. package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
  62. package/dist/managers/app/app.manager.d.ts +9 -0
  63. package/dist/managers/app/app.manager.d.ts.map +1 -1
  64. package/dist/managers/app/app.manager.utils.d.ts.map +1 -1
  65. package/dist/managers/logger/logger.manager.d.ts.map +1 -1
  66. package/dist/managers/request/request.manager.d.ts.map +1 -1
  67. package/dist/managers/request/request.manager.types.d.ts +2 -0
  68. package/dist/managers/request/request.manager.types.d.ts.map +1 -1
  69. package/dist/mocker/mocker.d.ts +1 -1
  70. package/dist/mocker/mocker.d.ts.map +1 -1
  71. package/dist/plugin/plugin.d.ts +2 -0
  72. package/dist/plugin/plugin.d.ts.map +1 -1
  73. package/dist/request/request.d.ts +1 -1
  74. package/dist/request/request.d.ts.map +1 -1
  75. package/dist/request/request.utils.d.ts.map +1 -1
  76. package/dist/utils/emitter.utils.d.ts.map +1 -1
  77. package/dist/utils/error.utils.d.ts +17 -0
  78. package/dist/utils/error.utils.d.ts.map +1 -0
  79. package/dist/utils/index.d.ts +1 -0
  80. package/dist/utils/index.d.ts.map +1 -1
  81. package/package.json +1 -1
  82. package/src/adapter/adapter.bindings.ts +46 -18
  83. package/src/adapter/adapter.utils.ts +47 -7
  84. package/src/cache/cache.events.ts +24 -8
  85. package/src/cache/cache.ts +109 -21
  86. package/src/cache/cache.utils.ts +33 -10
  87. package/src/client/client.ts +99 -7
  88. package/src/client/client.utils.ts +10 -4
  89. package/src/dispatcher/dispatcher.ts +273 -133
  90. package/src/http-adapter/http-adapter.fetch.ts +15 -3
  91. package/src/managers/app/app.manager.constants.ts +12 -1
  92. package/src/managers/app/app.manager.ts +43 -23
  93. package/src/managers/app/app.manager.utils.ts +8 -4
  94. package/src/managers/logger/logger.manager.ts +21 -8
  95. package/src/managers/request/request.manager.ts +7 -1
  96. package/src/managers/request/request.manager.types.ts +2 -0
  97. package/src/mocker/mocker.ts +14 -11
  98. package/src/plugin/plugin.ts +6 -0
  99. package/src/request/request.ts +31 -22
  100. package/src/request/request.utils.ts +23 -15
  101. package/src/utils/emitter.utils.ts +9 -2
  102. package/src/utils/error.utils.ts +29 -0
  103. package/src/utils/index.ts +1 -0
@@ -6,6 +6,8 @@ import type { RequestResponseEventType } from "managers";
6
6
  import type { OptimisticRollbackArgs, RequestInstance } from "request";
7
7
  import { scopeKey } from "request";
8
8
 
9
+ import { getThrownErrors } from "../../utils/fixtures.utils";
10
+
9
11
  const { resetMocks, startServer, stopServer, mockRequest } = createHttpMockingServer();
10
12
 
11
13
  const SERVER_ITEM = "server";
@@ -461,7 +463,7 @@ describe("Request [ Optimistic settlement ]", () => {
461
463
  });
462
464
 
463
465
  describe("when settlement callbacks fail", () => {
464
- it("should resolve normally and log when rollback throws", async () => {
466
+ it("should resolve normally, log and throw outside of the lifecycle when rollback throws", async () => {
465
467
  const { client, logError } = createSetup();
466
468
  const failure = new Error("Rollback failed");
467
469
  const request = client
@@ -473,9 +475,13 @@ describe("Request [ Optimistic settlement ]", () => {
473
475
  }));
474
476
  mockRequest(request, { status: 400 });
475
477
 
476
- const result = await request.send();
478
+ let result: Awaited<ReturnType<typeof request.send>> | undefined;
479
+ const thrown = await getThrownErrors(async () => {
480
+ result = await request.send();
481
+ });
477
482
 
478
- expect(result.status).toBe(400);
483
+ expect(result?.status).toBe(400);
484
+ expect(thrown).toStrictEqual([failure]);
479
485
  expect(logError).toHaveBeenCalledTimes(1);
480
486
  expect(logError.mock.calls[0][0].extra).toMatchObject({ error: failure, reason: "error" });
481
487
  });
@@ -492,12 +498,16 @@ describe("Request [ Optimistic settlement ]", () => {
492
498
  }));
493
499
  mockRequest(request, { status: 400 });
494
500
 
495
- const result = await request.send();
496
-
497
- expect(result.status).toBe(400);
498
- await waitFor(() => {
499
- expect(logError).toHaveBeenCalledTimes(1);
501
+ let result: Awaited<ReturnType<typeof request.send>> | undefined;
502
+ const thrown = await getThrownErrors(async () => {
503
+ result = await request.send();
504
+ await waitFor(() => {
505
+ expect(logError).toHaveBeenCalledTimes(1);
506
+ });
500
507
  });
508
+
509
+ expect(result?.status).toBe(400);
510
+ expect(thrown).toStrictEqual([failure]);
501
511
  expect(logError.mock.calls[0][0].extra).toMatchObject({ error: failure, reason: "error" });
502
512
  });
503
513
 
@@ -513,15 +523,19 @@ describe("Request [ Optimistic settlement ]", () => {
513
523
  const queryKey = scopeKey(request.queryKey, request.scope);
514
524
  client.submitDispatcher.stop(queryKey);
515
525
 
516
- const result = await request.send({
517
- onBeforeSent: ({ requestId }) => {
518
- queueMicrotask(() => {
519
- client.submitDispatcher.delete(queryKey, requestId, scopeKey(request.abortKey, request.scope));
520
- });
521
- },
526
+ let result: Awaited<ReturnType<typeof request.send>> | undefined;
527
+ const thrown = await getThrownErrors(async () => {
528
+ result = await request.send({
529
+ onBeforeSent: ({ requestId }) => {
530
+ queueMicrotask(() => {
531
+ client.submitDispatcher.delete(queryKey, requestId, scopeKey(request.abortKey, request.scope));
532
+ });
533
+ },
534
+ });
522
535
  });
523
536
 
524
- expect((result.error as Error).message).toBe(getErrorMessage("deleted").message);
537
+ expect((result?.error as Error | undefined)?.message).toBe(getErrorMessage("deleted").message);
538
+ expect(thrown).toStrictEqual([new Error("Rollback failed")]);
525
539
  expect(logError).toHaveBeenCalledTimes(1);
526
540
  });
527
541
 
@@ -537,9 +551,13 @@ describe("Request [ Optimistic settlement ]", () => {
537
551
  .setOptimistic(() => ({ invalidate: [list, other] }));
538
552
  mockRequest(request);
539
553
 
540
- const result = await request.send();
554
+ let result: Awaited<ReturnType<typeof request.send>> | undefined;
555
+ const thrown = await getThrownErrors(async () => {
556
+ result = await request.send();
557
+ });
541
558
 
542
- expect(result.success).toBeTrue();
559
+ expect(result?.success).toBeTrue();
560
+ expect(thrown).toStrictEqual([failure]);
543
561
  expect(invalidate).toHaveBeenCalledTimes(2);
544
562
  expect(invalidate).toHaveBeenLastCalledWith(other);
545
563
  expect(logError).toHaveBeenCalledTimes(1);
@@ -0,0 +1,408 @@
1
+ import { Client } from "client";
2
+ import { Request } from "request";
3
+
4
+ describe("Request [ Values ]", () => {
5
+ const client = new Client({ url: "http://values" });
6
+
7
+ describe("When params are put into the endpoint", () => {
8
+ const withParams = (endpoint: string, params: Record<string, string | number>) =>
9
+ client
10
+ .createRequest()({ endpoint })
11
+ .setParams(params as never).endpoint;
12
+
13
+ it.each([
14
+ { endpoint: "/users/:userId", params: { userId: 1 }, expected: "/users/1" },
15
+ { endpoint: "/users/:userId", params: { userId: "john" }, expected: "/users/john" },
16
+ { endpoint: "/users/:userId/posts/:postId", params: { userId: 1, postId: 2 }, expected: "/users/1/posts/2" },
17
+ { endpoint: "/users/:userId/posts/:postId", params: { postId: 2, userId: 1 }, expected: "/users/1/posts/2" },
18
+ { endpoint: ":version/users", params: { version: "v2" }, expected: "v2/users" },
19
+ { endpoint: "/compare/:id/with/:id", params: { id: 7 }, expected: "/compare/7/with/7" },
20
+ { endpoint: "/items/:id", params: { id: 0 }, expected: "/items/0" },
21
+ { endpoint: "/items/:id", params: { id: "" }, expected: "/items/" },
22
+ ])("should build $expected from $endpoint", ({ endpoint, params, expected }) => {
23
+ expect(withParams(endpoint, params as unknown as Record<string, string | number>)).toBe(expected);
24
+ });
25
+
26
+ it("should not let a short param name replace the beginning of a longer one", () => {
27
+ expect(withParams("/a/:id/b/:idx", { id: 1, idx: 2 })).toBe("/a/1/b/2");
28
+ expect(withParams("/a/:idx/b/:id", { id: 1, idx: 2 })).toBe("/a/2/b/1");
29
+ expect(withParams("/:user/:userId/:userIdentity", { user: "a", userId: "b", userIdentity: "c" })).toBe("/a/b/c");
30
+ });
31
+
32
+ it("should not treat a value as another param", () => {
33
+ expect(withParams("/:first/:second", { first: ":second", second: "value" })).toBe("/:second/value");
34
+ });
35
+
36
+ it.each(["$&", "$1", "$$", "$`", "$'", "a$b"])("should keep the %s value as it is", (value) => {
37
+ expect(withParams("/files/:name/raw", { name: value })).toBe(`/files/${value}/raw`);
38
+ });
39
+
40
+ it("should leave the params without a value in the endpoint", () => {
41
+ expect(withParams("/users/:userId/posts/:postId", { userId: 1 })).toBe("/users/1/posts/:postId");
42
+ });
43
+
44
+ it("should ignore the values which are not in the endpoint", () => {
45
+ expect(withParams("/users/:userId", { userId: 1, other: 2 })).toBe("/users/1");
46
+ });
47
+
48
+ it("should handle param names with special characters", () => {
49
+ expect(withParams("/files/:file.name/:a+b", { "file.name": "report", "a+b": 3 })).toBe("/files/report/3");
50
+ });
51
+
52
+ it("should not touch the endpoint without params", () => {
53
+ const request = client.createRequest()({ endpoint: "/time/12:30" });
54
+
55
+ expect(request.endpoint).toBe("/time/12:30");
56
+ expect(request.clone().endpoint).toBe("/time/12:30");
57
+ });
58
+
59
+ it("should replace the params from the template every time, not from the previous result", () => {
60
+ const request = client.createRequest()({ endpoint: "/users/:userId" });
61
+
62
+ const first = request.setParams({ userId: 1 });
63
+ const second = first.setParams({ userId: 2 });
64
+
65
+ expect(first.endpoint).toBe("/users/1");
66
+ expect(second.endpoint).toBe("/users/2");
67
+ expect(request.endpoint).toBe("/users/:userId");
68
+ });
69
+
70
+ it("should use the params given to send", async () => {
71
+ const request = client.createRequest<{ response: any }>()({ endpoint: "/users/:userId" });
72
+ const endpoints: string[] = [];
73
+ request.setMock(
74
+ ({ request: sent }) => {
75
+ endpoints.push(sent.endpoint);
76
+ return { data: null, status: 200 };
77
+ },
78
+ { requestTime: 0, responseTime: 0 },
79
+ );
80
+
81
+ await request.send({ params: { userId: 5 } });
82
+ await request.setParams({ userId: 6 }).send();
83
+
84
+ expect(endpoints).toEqual(["/users/5", "/users/6"]);
85
+ });
86
+ });
87
+
88
+ describe("When the payload is set", () => {
89
+ const request = client.createRequest<{ payload: any; response: any }>()({ endpoint: "/payload", method: "POST" });
90
+
91
+ it.each([
92
+ ["zero", 0],
93
+ ["false", false],
94
+ ["an empty string", ""],
95
+ ["an empty object", {}],
96
+ ["an empty array", []],
97
+ ["an object", { name: "John" }],
98
+ ["a nested object", { user: { tags: ["a", "b"] } }],
99
+ ["a string", "text"],
100
+ ["a number", 12.5],
101
+ ])("should keep %s as the payload", (_, payload) => {
102
+ expect(request.setPayload(payload).payload).toStrictEqual(payload);
103
+ });
104
+
105
+ it("should keep the reference of the payload", () => {
106
+ const payload = { name: "John" };
107
+
108
+ expect(request.setPayload(payload).payload).toBe(payload);
109
+ expect(request.setPayload(payload).setRetry(1).payload).toBe(payload);
110
+ });
111
+
112
+ it("should keep a falsy payload in the next clones", () => {
113
+ expect(request.setPayload(0).setRetry(2).setHeaders({ a: "b" }).payload).toBe(0);
114
+ expect(request.setPayload(false).clone().payload).toBe(false);
115
+ });
116
+
117
+ it("should replace the previous payload", () => {
118
+ expect(request.setPayload({ a: 1 }).setPayload({ b: 2 }).payload).toStrictEqual({ b: 2 });
119
+ expect(request.setPayload({ a: 1 }).setPayload(0).payload).toBe(0);
120
+ });
121
+
122
+ it("should remove the payload when it is set to null", () => {
123
+ expect(request.setPayload({ a: 1 }).setPayload(null).payload).toBeUndefined();
124
+ expect(request.setPayload({ a: 1 }).clone({ payload: null }).payload).toBeUndefined();
125
+ expect(request.setPayload({ a: 1 }).setPayload(null).setRetry(1).payload).toBeUndefined();
126
+ expect(request.setPayload(null).payload).toBeUndefined();
127
+ });
128
+
129
+ it("should keep the payload when the clone is given no payload", () => {
130
+ expect(request.setPayload({ a: 1 }).clone({ payload: undefined }).payload).toStrictEqual({ a: 1 });
131
+ expect(request.setPayload({ a: 1 }).clone({}).payload).toStrictEqual({ a: 1 });
132
+ });
133
+
134
+ it("should send no payload for null given to send instead of the payload set on the request", async () => {
135
+ const payloads: unknown[] = [];
136
+ const mocked = request.clone().setMock(
137
+ ({ request: sent }) => {
138
+ payloads.push(sent.payload);
139
+ return { data: null, status: 200 };
140
+ },
141
+ { requestTime: 0, responseTime: 0 },
142
+ );
143
+
144
+ await mocked.setPayload({ a: 1 }).send({ payload: null } as never);
145
+ await mocked.setPayload({ a: 1 }).send({ payload: undefined } as never);
146
+
147
+ expect(payloads).toStrictEqual([undefined, { a: 1 }]);
148
+ });
149
+
150
+ it("should keep the binary payloads untouched", () => {
151
+ const formData = new FormData();
152
+ const blob = new Blob(["content"]);
153
+ const buffer = new ArrayBuffer(8);
154
+
155
+ expect(request.setPayload(formData).clone().payload).toBe(formData);
156
+ expect(request.setPayload(blob).clone().payload).toBe(blob);
157
+ expect(request.setPayload(buffer).clone().payload).toBe(buffer);
158
+ });
159
+
160
+ it("should use the payload given to send", async () => {
161
+ const payloads: unknown[] = [];
162
+ const mocked = request.clone().setMock(
163
+ ({ request: sent }) => {
164
+ payloads.push(sent.payload);
165
+ return { data: null, status: 200 };
166
+ },
167
+ { requestTime: 0, responseTime: 0 },
168
+ );
169
+
170
+ await mocked.send({ payload: 0 });
171
+ await mocked.send({ payload: false });
172
+ await mocked.send({ payload: { a: 1 } });
173
+ await mocked.setPayload({ a: 1 }).send({ payload: { b: 2 } } as never);
174
+
175
+ expect(payloads).toStrictEqual([0, false, { a: 1 }, { b: 2 }]);
176
+ });
177
+ });
178
+
179
+ describe("When query params are set", () => {
180
+ const request = client.createRequest<{ queryParams: any }>()({ endpoint: "/query" });
181
+
182
+ it.each([
183
+ ["an object", { page: 1, search: "john" }],
184
+ ["an array value", { ids: [1, 2, 3] }],
185
+ ["a nested object", { filter: { role: "admin" } }],
186
+ ["a date", { since: new Date(0) }],
187
+ ["empty values", { a: null, b: undefined, c: "" }],
188
+ ["a string", "?page=1"],
189
+ ])("should keep %s", (_, queryParams) => {
190
+ expect(request.setQueryParams(queryParams).queryParams).toStrictEqual(queryParams);
191
+ });
192
+
193
+ it("should not change the endpoint", () => {
194
+ expect(request.setQueryParams({ page: 1 }).endpoint).toBe("/query");
195
+ });
196
+
197
+ it("should replace the previous query params instead of merging them", () => {
198
+ const updated = request.setQueryParams({ page: 1, search: "john" }).setQueryParams({ page: 2 });
199
+
200
+ expect(updated.queryParams).toStrictEqual({ page: 2 });
201
+ });
202
+
203
+ it.each([
204
+ [{ page: 1 }, "?page=1"],
205
+ [{ search: "a b&c=d" }, "?search=a%20b%26c%3Dd"],
206
+ [{ "weird key": "ż" }, "?weird%20key=%C5%BC"],
207
+ [{ ids: [1, 2, 3] }, "?ids[]=1&ids[]=2&ids[]=3"],
208
+ [{ ids: [] }, ""],
209
+ [{ a: null, b: undefined, c: "" }, ""],
210
+ [{ a: 0, b: false }, "?a=0&b=false"],
211
+ [{ since: new Date(0) }, "?since=1970-01-01T00%3A00%3A00.000Z"],
212
+ [{ filter: { role: "admin" } }, `?filter=${encodeURIComponent('{"role":"admin"}')}`],
213
+ ["page=1", "?page=1"],
214
+ ["?page=1", "?page=1"],
215
+ ["", ""],
216
+ [null, ""],
217
+ [{}, ""],
218
+ ])("should turn %o into the %s query string", (queryParams, expected) => {
219
+ expect(client.adapter.unstable_queryParamsMapper(queryParams)).toBe(expected);
220
+ });
221
+ });
222
+
223
+ describe("When keys are generated", () => {
224
+ const getUser = client.createRequest<{ queryParams?: any; payload?: any }>()({ endpoint: "/users/:userId" });
225
+
226
+ it("should give the same keys for the same request made twice", () => {
227
+ const first = getUser.setParams({ userId: 1 }).setQueryParams({ page: 1 });
228
+ const second = getUser.setParams({ userId: 1 }).setQueryParams({ page: 1 });
229
+
230
+ expect(first.cacheKey).toBe(second.cacheKey);
231
+ expect(first.queryKey).toBe(second.queryKey);
232
+ expect(first.abortKey).toBe(second.abortKey);
233
+ });
234
+
235
+ it("should give different cache and query keys for different params", () => {
236
+ const first = getUser.setParams({ userId: 1 });
237
+ const second = getUser.setParams({ userId: 2 });
238
+
239
+ expect(first.cacheKey).not.toBe(second.cacheKey);
240
+ expect(first.queryKey).not.toBe(second.queryKey);
241
+ });
242
+
243
+ it("should give different cache and query keys for different query params", () => {
244
+ const first = getUser.setQueryParams({ page: 1 });
245
+ const second = getUser.setQueryParams({ page: 2 });
246
+
247
+ expect(first.cacheKey).not.toBe(second.cacheKey);
248
+ expect(first.queryKey).not.toBe(second.queryKey);
249
+ });
250
+
251
+ it("should give different keys for different methods", () => {
252
+ const get = client.createRequest()({ endpoint: "/same", method: "GET" });
253
+ const post = client.createRequest()({ endpoint: "/same", method: "POST" });
254
+
255
+ expect(get.cacheKey).not.toBe(post.cacheKey);
256
+ expect(get.queryKey).not.toBe(post.queryKey);
257
+ expect(get.abortKey).not.toBe(post.abortKey);
258
+ });
259
+
260
+ it("should give different keys for different endpoints", () => {
261
+ const users = client.createRequest()({ endpoint: "/users" });
262
+ const posts = client.createRequest()({ endpoint: "/posts" });
263
+
264
+ expect(users.cacheKey).not.toBe(posts.cacheKey);
265
+ expect(users.queryKey).not.toBe(posts.queryKey);
266
+ expect(users.abortKey).not.toBe(posts.abortKey);
267
+ });
268
+
269
+ it("should not depend on the payload, headers or behavior options", () => {
270
+ const changed = getUser
271
+ .setPayload({ a: 1 })
272
+ .setHeaders({ a: "b" })
273
+ .setRetry(3)
274
+ .setQueued(true)
275
+ .setOffline(false)
276
+ .setCache(false);
277
+
278
+ expect(changed.cacheKey).toBe(getUser.cacheKey);
279
+ expect(changed.queryKey).toBe(getUser.queryKey);
280
+ expect(changed.abortKey).toBe(getUser.abortKey);
281
+ });
282
+
283
+ it("should share the abort key between all the params of one endpoint", () => {
284
+ expect(getUser.setParams({ userId: 1 }).abortKey).toBe(getUser.setParams({ userId: 2 }).abortKey);
285
+ });
286
+
287
+ it("should use a different abort key for the cancelable requests", () => {
288
+ expect(getUser.setCancelable(true).abortKey).not.toBe(getUser.abortKey);
289
+ });
290
+
291
+ it("should use the key mappers of the client", () => {
292
+ const custom = new Client({ url: "http://values" })
293
+ .setCacheKeyMapper((request) => `cache:${request.endpoint}`)
294
+ .setQueryKeyMapper((request) => `query:${request.endpoint}`)
295
+ .setAbortKeyMapper((request) => `abort:${request.endpoint}`);
296
+ const request = custom.createRequest()({ endpoint: "/users/:userId" }).setParams({ userId: 1 });
297
+
298
+ expect([request.cacheKey, request.queryKey, request.abortKey]).toEqual([
299
+ "cache:/users/1",
300
+ "query:/users/1",
301
+ "abort:/users/1",
302
+ ]);
303
+ });
304
+
305
+ it("should not put the scope into the keys of the request", () => {
306
+ const scoped = getUser.setScope("session");
307
+
308
+ expect(scoped.scope).toBe("session");
309
+ expect(scoped.cacheKey).toBe(getUser.cacheKey);
310
+ expect(scoped.setRetry(1).scope).toBe("session");
311
+ });
312
+ });
313
+
314
+ describe("When the request is dumped to JSON", () => {
315
+ const createConfigured = () =>
316
+ client
317
+ .createRequest<{ payload: any; queryParams: any; response: any }>()({
318
+ endpoint: "/users/:userId",
319
+ method: "PATCH",
320
+ retry: 2,
321
+ disableRequestInterceptors: true,
322
+ })
323
+ .setParams({ userId: 1 })
324
+ .setQueryParams({ page: 1 })
325
+ .setPayload({ name: "John" })
326
+ .setHeaders({ "X-Test": "1" })
327
+ .setOptions({ timeout: 100 })
328
+ .setRetryTime(700)
329
+ .setCacheTime(10)
330
+ .setStaleTime(20)
331
+ .setQueued(true)
332
+ .setOffline(false)
333
+ .setCancelable(true)
334
+ .setAuth(false)
335
+ .setUsed(true)
336
+ .setDeduplicate(true)
337
+ .setDeduplicateTime(50)
338
+ .setStructuralSharing(false)
339
+ .setScope("session");
340
+
341
+ it("should recreate an equal request", () => {
342
+ const request = createConfigured();
343
+
344
+ const recreated = Request.fromJSON(client, request.toJSON());
345
+
346
+ expect(recreated).toBeInstanceOf(Request);
347
+ expect(recreated.toJSON()).toStrictEqual(request.toJSON());
348
+ });
349
+
350
+ it("should survive being stringified", () => {
351
+ const request = createConfigured();
352
+
353
+ const stored = JSON.stringify(request);
354
+
355
+ const recreated = client.fromJSON(JSON.parse(stored));
356
+
357
+ expect(recreated.toJSON()).toEqual(request.toJSON());
358
+ expect(recreated.endpoint).toBe("/users/1");
359
+ expect(recreated.payload).toStrictEqual({ name: "John" });
360
+ });
361
+
362
+ it("should keep the keys set by hand", () => {
363
+ const request = createConfigured().setCacheKey("cache").setQueryKey("query").setAbortKey("abort");
364
+
365
+ const recreated = Request.fromJSON(client, request.toJSON());
366
+
367
+ expect([recreated.cacheKey, recreated.queryKey, recreated.abortKey]).toEqual(["cache", "query", "abort"]);
368
+ expect(recreated.setRetry(1).cacheKey).toBe("cache");
369
+ });
370
+
371
+ it("should keep generating the keys of a recreated request", () => {
372
+ const request = client.createRequest()({ endpoint: "/users/:userId" }).setParams({ userId: 1 });
373
+
374
+ const recreated = Request.fromJSON(client, request.toJSON());
375
+
376
+ expect(recreated.cacheKey).toBe(request.cacheKey);
377
+ expect(recreated.setParams({ userId: 2 }).cacheKey).toBe(request.setParams({ userId: 2 }).cacheKey);
378
+ });
379
+
380
+ it("should keep the template endpoint to accept other params", () => {
381
+ const recreated = Request.fromJSON(client, createConfigured().toJSON());
382
+
383
+ expect(recreated.requestOptions.endpoint).toBe("/users/:userId");
384
+ expect(recreated.setParams({ userId: 9 }).endpoint).toBe("/users/9");
385
+ });
386
+
387
+ it("should tell if the request had a mock", () => {
388
+ const request = createConfigured();
389
+
390
+ expect(request.toJSON().hasMock).toBe(false);
391
+ request.setMock(() => ({ data: null, status: 200 }));
392
+
393
+ expect(request.toJSON()).toMatchObject({ hasMock: true, isMockerEnabled: true });
394
+ });
395
+
396
+ it("should not dump the functions", () => {
397
+ const request = createConfigured()
398
+ .setRetryOnError(() => true)
399
+ .setResponseMapper((response) => response)
400
+ .setRequestMapper((mapped) => mapped)
401
+ .setPayloadMapper((payload) => payload);
402
+
403
+ const values = Object.values(request.toJSON());
404
+
405
+ expect(values.some((value) => typeof value === "function")).toBe(false);
406
+ });
407
+ });
408
+ });