@hyper-fetch/axios 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.
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
import { Client, getErrorMessage, Plugin, scopeKey } from "@hyper-fetch/core";
|
|
2
|
+
import http from "http";
|
|
3
|
+
import type { AddressInfo } from "net";
|
|
4
|
+
|
|
5
|
+
import { AxiosAdapter } from "../../../src/adapter/adapter";
|
|
6
|
+
|
|
7
|
+
type ExchangeType = {
|
|
8
|
+
req: http.IncomingMessage;
|
|
9
|
+
res: http.ServerResponse;
|
|
10
|
+
body: string;
|
|
11
|
+
/** Resolves when the client side of the connection is closed */
|
|
12
|
+
closed: Promise<void>;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** A real HTTP server that answers only when the test tells it to. */
|
|
16
|
+
const createGatedServer = () => {
|
|
17
|
+
const pending: ExchangeType[] = [];
|
|
18
|
+
const waiters: ((exchange: ExchangeType) => void)[] = [];
|
|
19
|
+
const server = http.createServer((req, res) => {
|
|
20
|
+
let body = "";
|
|
21
|
+
req.setEncoding("utf8");
|
|
22
|
+
req.on("data", (chunk: string) => {
|
|
23
|
+
body += chunk;
|
|
24
|
+
});
|
|
25
|
+
req.on("end", () => {
|
|
26
|
+
const closed = new Promise<void>((resolve) => {
|
|
27
|
+
res.on("close", () => resolve());
|
|
28
|
+
});
|
|
29
|
+
const exchange: ExchangeType = { req, res, body, closed };
|
|
30
|
+
const waiter = waiters.shift();
|
|
31
|
+
if (waiter) {
|
|
32
|
+
waiter(exchange);
|
|
33
|
+
} else {
|
|
34
|
+
pending.push(exchange);
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
return {
|
|
40
|
+
start: () =>
|
|
41
|
+
new Promise<string>((resolve) => {
|
|
42
|
+
server.listen(0, "127.0.0.1", () => {
|
|
43
|
+
resolve(`http://127.0.0.1:${(server.address() as AddressInfo).port}`);
|
|
44
|
+
});
|
|
45
|
+
}),
|
|
46
|
+
stop: () =>
|
|
47
|
+
new Promise<void>((resolve) => {
|
|
48
|
+
server.closeAllConnections();
|
|
49
|
+
server.close(() => resolve());
|
|
50
|
+
}),
|
|
51
|
+
/** The next request that reached the server */
|
|
52
|
+
next: () =>
|
|
53
|
+
new Promise<ExchangeType>((resolve) => {
|
|
54
|
+
const exchange = pending.shift();
|
|
55
|
+
if (exchange) {
|
|
56
|
+
resolve(exchange);
|
|
57
|
+
} else {
|
|
58
|
+
waiters.push(resolve);
|
|
59
|
+
}
|
|
60
|
+
}),
|
|
61
|
+
reset: () => {
|
|
62
|
+
pending.length = 0;
|
|
63
|
+
waiters.length = 0;
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const write = (res: http.ServerResponse, chunk: string) =>
|
|
69
|
+
new Promise<void>((resolve) => {
|
|
70
|
+
res.write(chunk, () => resolve());
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const json = (res: http.ServerResponse, status: number, data: unknown) => {
|
|
74
|
+
const body = JSON.stringify(data);
|
|
75
|
+
res.writeHead(status, {
|
|
76
|
+
"Content-Type": "application/json",
|
|
77
|
+
"Content-Length": Buffer.byteLength(body),
|
|
78
|
+
"X-Trace": "abc",
|
|
79
|
+
});
|
|
80
|
+
res.end(body);
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
describe("Axios Adapter [ Lifecycle ]", () => {
|
|
84
|
+
const server = createGatedServer();
|
|
85
|
+
let baseUrl = "";
|
|
86
|
+
|
|
87
|
+
const createSetup = () => {
|
|
88
|
+
const onRequestError = vi.fn();
|
|
89
|
+
const onRequestSuccess = vi.fn();
|
|
90
|
+
const onRequestFinished = vi.fn();
|
|
91
|
+
const plugin = new Plugin({ name: "outcomes" })
|
|
92
|
+
.onRequestError(onRequestError)
|
|
93
|
+
.onRequestSuccess(onRequestSuccess)
|
|
94
|
+
.onRequestFinished(onRequestFinished);
|
|
95
|
+
const client = new Client({ url: baseUrl }).setAdapter(AxiosAdapter).addPlugin(plugin);
|
|
96
|
+
return { client, onRequestError, onRequestSuccess, onRequestFinished };
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
beforeAll(async () => {
|
|
100
|
+
baseUrl = await server.start();
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
afterEach(() => {
|
|
104
|
+
server.reset();
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
afterAll(async () => {
|
|
108
|
+
await server.stop();
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
describe("when the request is aborted", () => {
|
|
112
|
+
it("should resolve with the abort error and close the connection", async () => {
|
|
113
|
+
const { client, onRequestError, onRequestFinished } = createSetup();
|
|
114
|
+
const request = client.createRequest<{ response: { ok: boolean } }>()({ endpoint: "/abort" });
|
|
115
|
+
|
|
116
|
+
const sent = request.send();
|
|
117
|
+
const exchange = await server.next();
|
|
118
|
+
request.abort();
|
|
119
|
+
const response = await sent;
|
|
120
|
+
await exchange.closed;
|
|
121
|
+
|
|
122
|
+
expect(response.success).toBe(false);
|
|
123
|
+
expect(response.data).toBeNull();
|
|
124
|
+
expect(response.error).toEqual(getErrorMessage("abort"));
|
|
125
|
+
expect(response.status).toBe(0);
|
|
126
|
+
expect(onRequestError).toHaveBeenCalledTimes(1);
|
|
127
|
+
expect(onRequestFinished).toHaveBeenCalledTimes(1);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it("should not retry an aborted request", async () => {
|
|
131
|
+
const { client } = createSetup();
|
|
132
|
+
const request = client.createRequest<{ response: { ok: boolean } }>()({
|
|
133
|
+
endpoint: "/abort-retry",
|
|
134
|
+
retry: 3,
|
|
135
|
+
retryTime: 0,
|
|
136
|
+
});
|
|
137
|
+
const started = vi.fn();
|
|
138
|
+
client.requestManager.events.onRequestStart(started);
|
|
139
|
+
|
|
140
|
+
const sent = request.send();
|
|
141
|
+
await server.next();
|
|
142
|
+
request.abort();
|
|
143
|
+
const response = await sent;
|
|
144
|
+
|
|
145
|
+
expect(response.error).toEqual(getErrorMessage("abort"));
|
|
146
|
+
expect(started).toHaveBeenCalledTimes(1);
|
|
147
|
+
// Nothing is left to run or to retry
|
|
148
|
+
expect(client.fetchDispatcher.getAllRunningRequests()).toHaveLength(0);
|
|
149
|
+
expect(client.fetchDispatcher.getQueue(scopeKey(request.queryKey, request.scope)).requests).toHaveLength(0);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it("should abort while the body is still downloading", async () => {
|
|
153
|
+
const { client, onRequestError } = createSetup();
|
|
154
|
+
const request = client.createRequest<{ response: string }>()({ endpoint: "/abort-body" });
|
|
155
|
+
let downloaded = () => {};
|
|
156
|
+
const firstProgress = new Promise<void>((resolve) => {
|
|
157
|
+
downloaded = resolve;
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
const sent = request.send({ onDownloadProgress: () => downloaded() });
|
|
161
|
+
const exchange = await server.next();
|
|
162
|
+
exchange.res.writeHead(200, { "Content-Type": "text/plain", "Content-Length": "10" });
|
|
163
|
+
await write(exchange.res, "12345");
|
|
164
|
+
await firstProgress;
|
|
165
|
+
request.abort();
|
|
166
|
+
const response = await sent;
|
|
167
|
+
await exchange.closed;
|
|
168
|
+
|
|
169
|
+
expect(response.error).toEqual(getErrorMessage("abort"));
|
|
170
|
+
expect(response.data).toBeNull();
|
|
171
|
+
expect(onRequestError).toHaveBeenCalledTimes(1);
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
it("should not abort other requests that are in flight", async () => {
|
|
175
|
+
const { client } = createSetup();
|
|
176
|
+
const first = client.createRequest<{ response: { id: number } }>()({ endpoint: "/first" });
|
|
177
|
+
const second = client.createRequest<{ response: { id: number } }>()({ endpoint: "/second" });
|
|
178
|
+
|
|
179
|
+
const sentFirst = first.send();
|
|
180
|
+
const firstExchange = await server.next();
|
|
181
|
+
const sentSecond = second.send();
|
|
182
|
+
const secondExchange = await server.next();
|
|
183
|
+
first.abort();
|
|
184
|
+
json(secondExchange.res, 200, { id: 2 });
|
|
185
|
+
const [firstResponse, secondResponse] = await Promise.all([sentFirst, sentSecond]);
|
|
186
|
+
await firstExchange.closed;
|
|
187
|
+
|
|
188
|
+
expect(firstResponse.error).toEqual(getErrorMessage("abort"));
|
|
189
|
+
expect(secondResponse.data).toEqual({ id: 2 });
|
|
190
|
+
});
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
describe("when the response arrives in several pieces", () => {
|
|
194
|
+
it("should report the request end and the response start once", async () => {
|
|
195
|
+
const { client } = createSetup();
|
|
196
|
+
const request = client.createRequest<{ response: string }>()({ endpoint: "/pieces" });
|
|
197
|
+
const onResponseStart = vi.fn();
|
|
198
|
+
const requestEnded = vi.fn();
|
|
199
|
+
const loaded: number[] = [];
|
|
200
|
+
let progressed = () => {};
|
|
201
|
+
let nextProgress = new Promise<void>((resolve) => {
|
|
202
|
+
progressed = resolve;
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
const sent = request.send({
|
|
206
|
+
onResponseStart,
|
|
207
|
+
onUploadProgress: ({ loaded: bytes, total }) => bytes === total && requestEnded(),
|
|
208
|
+
onDownloadProgress: (event) => {
|
|
209
|
+
loaded.push(event.loaded);
|
|
210
|
+
progressed();
|
|
211
|
+
},
|
|
212
|
+
});
|
|
213
|
+
const exchange = await server.next();
|
|
214
|
+
exchange.res.writeHead(200, { "Content-Type": "text/plain", "Content-Length": "9" });
|
|
215
|
+
for (const piece of ["abc", "def"]) {
|
|
216
|
+
// eslint-disable-next-line no-await-in-loop
|
|
217
|
+
await write(exchange.res, piece);
|
|
218
|
+
// eslint-disable-next-line no-await-in-loop
|
|
219
|
+
await nextProgress;
|
|
220
|
+
nextProgress = new Promise<void>((resolve) => {
|
|
221
|
+
progressed = resolve;
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
exchange.res.end("ghi");
|
|
225
|
+
const response = await sent;
|
|
226
|
+
|
|
227
|
+
expect(response.data).toBe("abcdefghi");
|
|
228
|
+
expect(onResponseStart).toHaveBeenCalledTimes(1);
|
|
229
|
+
// Loaded bytes never go backwards and end at the full size
|
|
230
|
+
expect([...loaded].sort((a, b) => a - b)).toEqual(loaded);
|
|
231
|
+
expect(loaded.at(-1)).toBe(9);
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it("should keep the response start time of the first piece", async () => {
|
|
235
|
+
const { client } = createSetup();
|
|
236
|
+
const request = client.createRequest<{ response: string }>()({ endpoint: "/timestamps" });
|
|
237
|
+
const starts: number[] = [];
|
|
238
|
+
let progressed = () => {};
|
|
239
|
+
const firstProgress = new Promise<void>((resolve) => {
|
|
240
|
+
progressed = resolve;
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
const sent = request.send({
|
|
244
|
+
onDownloadProgress: (event) => {
|
|
245
|
+
starts.push(event.startTimestamp);
|
|
246
|
+
progressed();
|
|
247
|
+
},
|
|
248
|
+
});
|
|
249
|
+
const exchange = await server.next();
|
|
250
|
+
exchange.res.writeHead(200, { "Content-Type": "text/plain", "Content-Length": "6" });
|
|
251
|
+
await write(exchange.res, "abc");
|
|
252
|
+
await firstProgress;
|
|
253
|
+
exchange.res.end("def");
|
|
254
|
+
await sent;
|
|
255
|
+
|
|
256
|
+
expect(new Set(starts.filter((_, index) => index > 0)).size).toBe(1);
|
|
257
|
+
});
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
describe("when the response has no body", () => {
|
|
261
|
+
it.each([204, 205, 304])("should still report the response start for a %i", async (status) => {
|
|
262
|
+
const { client, onRequestSuccess, onRequestError } = createSetup();
|
|
263
|
+
const request = client.createRequest<{ response: null }>()({ endpoint: "/empty" });
|
|
264
|
+
const onResponseStart = vi.fn();
|
|
265
|
+
const onRequestStart = vi.fn();
|
|
266
|
+
|
|
267
|
+
const sent = request.send({ onResponseStart, onRequestStart });
|
|
268
|
+
const exchange = await server.next();
|
|
269
|
+
exchange.res.writeHead(status);
|
|
270
|
+
exchange.res.end();
|
|
271
|
+
const response = await sent;
|
|
272
|
+
|
|
273
|
+
expect(response.status).toBe(status);
|
|
274
|
+
expect(onRequestStart).toHaveBeenCalledTimes(1);
|
|
275
|
+
expect(onResponseStart).toHaveBeenCalledTimes(1);
|
|
276
|
+
expect(onRequestSuccess.mock.calls.length + onRequestError.mock.calls.length).toBe(1);
|
|
277
|
+
});
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
describe("when the request fails", () => {
|
|
281
|
+
it.each([400, 401, 403, 404, 409, 422, 429, 500, 502, 503])(
|
|
282
|
+
"should return the %i status, the axios error and the response headers",
|
|
283
|
+
async (status) => {
|
|
284
|
+
const { client, onRequestError } = createSetup();
|
|
285
|
+
const request = client.createRequest<{ response: { ok: boolean } }>()({ endpoint: "/failing" });
|
|
286
|
+
|
|
287
|
+
const sent = request.send();
|
|
288
|
+
const exchange = await server.next();
|
|
289
|
+
json(exchange.res, status, { message: "Nope" });
|
|
290
|
+
const response = await sent;
|
|
291
|
+
|
|
292
|
+
expect(response.success).toBe(false);
|
|
293
|
+
expect(response.data).toBeNull();
|
|
294
|
+
expect(response.status).toBe(status);
|
|
295
|
+
expect((response.error as { response?: { data: unknown } }).response?.data).toEqual({ message: "Nope" });
|
|
296
|
+
expect(response.extra?.headers["x-trace"]).toBe("abc");
|
|
297
|
+
expect(onRequestError).toHaveBeenCalledTimes(1);
|
|
298
|
+
},
|
|
299
|
+
);
|
|
300
|
+
|
|
301
|
+
it("should return the system status and empty headers when the connection breaks", async () => {
|
|
302
|
+
const { client, onRequestError } = createSetup();
|
|
303
|
+
const request = client.createRequest<{ response: { ok: boolean } }>()({ endpoint: "/broken" });
|
|
304
|
+
|
|
305
|
+
const sent = request.send();
|
|
306
|
+
const exchange = await server.next();
|
|
307
|
+
exchange.req.socket.destroy();
|
|
308
|
+
const response = await sent;
|
|
309
|
+
|
|
310
|
+
expect(response.success).toBe(false);
|
|
311
|
+
expect(response.status).toBe(0);
|
|
312
|
+
expect(response.error).toBeInstanceOf(Error);
|
|
313
|
+
expect(response.extra).toEqual({ headers: {} });
|
|
314
|
+
expect(onRequestError).toHaveBeenCalledTimes(1);
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
it("should fail with the axios timeout error when the `timeout` option runs out", async () => {
|
|
318
|
+
const { client } = createSetup();
|
|
319
|
+
const request = client.createRequest<{ response: { ok: boolean } }>()({
|
|
320
|
+
endpoint: "/slow",
|
|
321
|
+
options: { timeout: 30 },
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
const sent = request.send();
|
|
325
|
+
const exchange = await server.next();
|
|
326
|
+
const response = await sent;
|
|
327
|
+
await exchange.closed;
|
|
328
|
+
|
|
329
|
+
expect(response.success).toBe(false);
|
|
330
|
+
expect(response.status).toBe(0);
|
|
331
|
+
expect((response.error as { code?: string }).code).toBe("ECONNABORTED");
|
|
332
|
+
expect(response.extra).toEqual({ headers: {} });
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
it("should retry a failed request and succeed", async () => {
|
|
336
|
+
const { client } = createSetup();
|
|
337
|
+
const request = client.createRequest<{ response: { ok: boolean } }>()({
|
|
338
|
+
endpoint: "/flaky",
|
|
339
|
+
retry: 2,
|
|
340
|
+
retryTime: 0,
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
const sent = request.send();
|
|
344
|
+
json((await server.next()).res, 503, { message: "Busy" });
|
|
345
|
+
json((await server.next()).res, 503, { message: "Busy" });
|
|
346
|
+
json((await server.next()).res, 200, { ok: true });
|
|
347
|
+
const response = await sent;
|
|
348
|
+
|
|
349
|
+
expect(response.data).toEqual({ ok: true });
|
|
350
|
+
expect(response.status).toBe(200);
|
|
351
|
+
});
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
describe("when sending data", () => {
|
|
355
|
+
it("should send the method, headers, query params and a JSON payload", async () => {
|
|
356
|
+
const { client } = createSetup();
|
|
357
|
+
const request = client
|
|
358
|
+
.createRequest<{
|
|
359
|
+
response: { ok: boolean };
|
|
360
|
+
payload: { name: string };
|
|
361
|
+
queryParams: { page: number; tags: string[] };
|
|
362
|
+
}>()({
|
|
363
|
+
endpoint: "/users/:id",
|
|
364
|
+
method: "PATCH",
|
|
365
|
+
headers: { "X-Custom": "yes" },
|
|
366
|
+
})
|
|
367
|
+
.setParams({ id: 7 });
|
|
368
|
+
|
|
369
|
+
const sent = request.send({ payload: { name: "Zażółć" }, queryParams: { page: 2, tags: ["a", "b"] } });
|
|
370
|
+
const exchange = await server.next();
|
|
371
|
+
json(exchange.res, 200, { ok: true });
|
|
372
|
+
const response = await sent;
|
|
373
|
+
|
|
374
|
+
expect(exchange.req.method).toBe("PATCH");
|
|
375
|
+
expect(exchange.req.url).toBe("/users/7?page=2&tags[]=a&tags[]=b");
|
|
376
|
+
expect(exchange.req.headers["x-custom"]).toBe("yes");
|
|
377
|
+
expect(exchange.req.headers["content-type"]).toContain("application/json");
|
|
378
|
+
expect(JSON.parse(exchange.body)).toEqual({ name: "Zażółć" });
|
|
379
|
+
expect(response.data).toEqual({ ok: true });
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
it.each(["GET", "POST", "PUT", "PATCH", "DELETE"] as const)("should send a %s request", async (method) => {
|
|
383
|
+
const { client } = createSetup();
|
|
384
|
+
const request = client.createRequest<{ response: { ok: boolean } }>()({ endpoint: "/method", method });
|
|
385
|
+
|
|
386
|
+
const sent = request.send();
|
|
387
|
+
const exchange = await server.next();
|
|
388
|
+
json(exchange.res, 200, { ok: true });
|
|
389
|
+
const response = await sent;
|
|
390
|
+
|
|
391
|
+
expect(exchange.req.method).toBe(method);
|
|
392
|
+
expect(response.data).toEqual({ ok: true });
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
it("should pass axios options through", async () => {
|
|
396
|
+
const { client } = createSetup();
|
|
397
|
+
const request = client.createRequest<{ response: string }>()({
|
|
398
|
+
endpoint: "/options",
|
|
399
|
+
options: { responseType: "text", transformResponse: (data: string) => data.toUpperCase() },
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
const sent = request.send();
|
|
403
|
+
const exchange = await server.next();
|
|
404
|
+
json(exchange.res, 200, { ok: true });
|
|
405
|
+
const response = await sent;
|
|
406
|
+
|
|
407
|
+
expect(response.data).toBe('{"OK":TRUE}');
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
it("should report the upload of a payload up to its full size", async () => {
|
|
411
|
+
const { client } = createSetup();
|
|
412
|
+
const request = client.createRequest<{ response: { ok: boolean }; payload: { text: string } }>()({
|
|
413
|
+
endpoint: "/upload",
|
|
414
|
+
method: "POST",
|
|
415
|
+
});
|
|
416
|
+
const uploads: { loaded: number; total: number }[] = [];
|
|
417
|
+
|
|
418
|
+
const sent = request.send({
|
|
419
|
+
payload: { text: "x".repeat(2000) },
|
|
420
|
+
onUploadProgress: ({ loaded, total }) => uploads.push({ loaded, total }),
|
|
421
|
+
});
|
|
422
|
+
const exchange = await server.next();
|
|
423
|
+
json(exchange.res, 200, { ok: true });
|
|
424
|
+
await sent;
|
|
425
|
+
|
|
426
|
+
expect(exchange.body.length).toBeGreaterThan(2000);
|
|
427
|
+
expect(uploads.length).toBeGreaterThan(0);
|
|
428
|
+
expect(uploads.at(-1)?.loaded).toBe(uploads.at(-1)?.total);
|
|
429
|
+
});
|
|
430
|
+
});
|
|
431
|
+
|
|
432
|
+
describe("when several requests run", () => {
|
|
433
|
+
it("should keep concurrent responses apart", async () => {
|
|
434
|
+
const { client } = createSetup();
|
|
435
|
+
const request = client.createRequest<{ response: { id: string }; queryParams: { id: string } }>()({
|
|
436
|
+
endpoint: "/concurrent",
|
|
437
|
+
});
|
|
438
|
+
|
|
439
|
+
const sent = ["a", "b", "c", "d"].map((id) => request.send({ queryParams: { id } }));
|
|
440
|
+
const exchanges = await Promise.all(sent.map(() => server.next()));
|
|
441
|
+
// Answer in reverse order
|
|
442
|
+
[...exchanges].reverse().forEach((exchange) => {
|
|
443
|
+
const id = new URL(exchange.req.url ?? "", baseUrl).searchParams.get("id");
|
|
444
|
+
json(exchange.res, 200, { id });
|
|
445
|
+
});
|
|
446
|
+
const responses = await Promise.all(sent);
|
|
447
|
+
|
|
448
|
+
expect(responses.map((response) => response.data?.id)).toEqual(["a", "b", "c", "d"]);
|
|
449
|
+
});
|
|
450
|
+
|
|
451
|
+
it("should fire the lifecycle callbacks once and in order", async () => {
|
|
452
|
+
const { client } = createSetup();
|
|
453
|
+
const request = client.createRequest<{ response: { ok: boolean } }>()({ endpoint: "/order" });
|
|
454
|
+
const order: string[] = [];
|
|
455
|
+
|
|
456
|
+
const sent = request.send({
|
|
457
|
+
onBeforeSent: () => order.push("before"),
|
|
458
|
+
onRequestStart: () => order.push("request-start"),
|
|
459
|
+
onResponseStart: () => order.push("response-start"),
|
|
460
|
+
onResponse: () => order.push("response"),
|
|
461
|
+
});
|
|
462
|
+
const exchange = await server.next();
|
|
463
|
+
json(exchange.res, 200, { ok: true });
|
|
464
|
+
await sent;
|
|
465
|
+
|
|
466
|
+
expect(order).toEqual(["before", "request-start", "response-start", "response"]);
|
|
467
|
+
});
|
|
468
|
+
});
|
|
469
|
+
});
|
|
@@ -68,7 +68,7 @@ describe("Axios Adapter [ Base ]", () => {
|
|
|
68
68
|
expect(error).toBeInstanceOf(Error);
|
|
69
69
|
expect(data).toStrictEqual(null);
|
|
70
70
|
expect(status).toBe(0); // systemErrorStatus default
|
|
71
|
-
expect(extra?.headers).
|
|
71
|
+
expect(extra?.headers).toEqual({});
|
|
72
72
|
|
|
73
73
|
// Restore original XMLHttpRequest
|
|
74
74
|
global.XMLHttpRequest = originalXHR;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../src/adapter/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAwB,MAAM,mBAAmB,CAAC;AAClE,OAAO,KAAK,EAAE,MAAM,IAAI,YAAY,EAAE,kBAAkB,EAAE,MAAM,OAAO,CAAC;AAGxE,OAAO,KAAK,EAAE,UAAU,EAAmB,MAAM,iBAAiB,CAAC;AAEnE,MAAM,MAAM,gBAAgB,GAAG,OAAO,YAAY,CAAC;AAEnD,4HAA4H;AAC5H,eAAO,MAAM,YAAY,
|
|
1
|
+
{"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../src/adapter/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAwB,MAAM,mBAAmB,CAAC;AAClE,OAAO,KAAK,EAAE,MAAM,IAAI,YAAY,EAAE,kBAAkB,EAAE,MAAM,OAAO,CAAC;AAGxE,OAAO,KAAK,EAAE,UAAU,EAAmB,MAAM,iBAAiB,CAAC;AAEnE,MAAM,MAAM,gBAAgB,GAAG,OAAO,YAAY,CAAC;AAEnD,4HAA4H;AAC5H,eAAO,MAAM,YAAY,ylBAwGtB,CAAC"}
|
package/dist/index.mjs
CHANGED
|
@@ -13,10 +13,21 @@ var AxiosAdapter = new Adapter({
|
|
|
13
13
|
const fullUrl = `${url}${endpoint}${queryParams}`;
|
|
14
14
|
onBeforeRequest();
|
|
15
15
|
const controller = getAbortController();
|
|
16
|
-
const unmountListener =
|
|
16
|
+
const unmountListener = createAbortListener({
|
|
17
17
|
status: 0,
|
|
18
18
|
extra: { headers: {} }
|
|
19
19
|
});
|
|
20
|
+
if (controller?.signal.aborted) {
|
|
21
|
+
unmountListener();
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
let hasResponseStarted = false;
|
|
25
|
+
const startResponse = () => {
|
|
26
|
+
if (hasResponseStarted) return;
|
|
27
|
+
hasResponseStarted = true;
|
|
28
|
+
onRequestEnd();
|
|
29
|
+
onResponseStart();
|
|
30
|
+
};
|
|
20
31
|
onRequestStart();
|
|
21
32
|
axios({
|
|
22
33
|
...adapterOptions,
|
|
@@ -29,22 +40,24 @@ var AxiosAdapter = new Adapter({
|
|
|
29
40
|
onRequestProgress(progressEvent);
|
|
30
41
|
},
|
|
31
42
|
onDownloadProgress: (progressEvent) => {
|
|
32
|
-
|
|
33
|
-
onResponseStart();
|
|
43
|
+
startResponse();
|
|
34
44
|
onResponseProgress(progressEvent);
|
|
35
45
|
}
|
|
36
46
|
}).then((response) => {
|
|
47
|
+
startResponse();
|
|
48
|
+
onResponseEnd();
|
|
37
49
|
onSuccess({
|
|
38
50
|
data: response.data,
|
|
39
51
|
status: response.status,
|
|
40
52
|
extra: { headers: response.headers }
|
|
41
53
|
});
|
|
42
|
-
onResponseEnd();
|
|
43
54
|
}).catch((error) => {
|
|
55
|
+
if (controller?.signal.aborted) return;
|
|
56
|
+
if (error.response) startResponse();
|
|
44
57
|
onError({
|
|
45
58
|
error,
|
|
46
59
|
status: error.response?.status || adapter.systemErrorStatus,
|
|
47
|
-
extra: { headers: error.response?.headers }
|
|
60
|
+
extra: { headers: error.response?.headers ?? {} }
|
|
48
61
|
});
|
|
49
62
|
}).finally(() => {
|
|
50
63
|
unmountListener();
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/adapter/adapter.ts"],"sourcesContent":["import { Adapter, stringifyQueryParams } from \"@hyper-fetch/core\";\nimport type { Method as AxiosMethods, AxiosRequestConfig } from \"axios\";\nimport axios, { AxiosHeaders } from \"axios\";\n\nimport type { AxiosExtra, RawAxiosHeaders } from \"./adapter.types\";\n\nexport type AxiosAdapterType = typeof AxiosAdapter;\n\n/** Pre-configured adapter that uses Axios as the underlying HTTP transport. Supports upload/download progress and abort. */\nexport const AxiosAdapter = new Adapter<\n Omit<AxiosRequestConfig, \"url\" | \"baseURL\" | \"method\" | \"onUploadProgress\" | \"onDownloadProgress\" | \"data\">,\n AxiosMethods,\n number,\n AxiosExtra\n>({\n name: \"axios-adapter\",\n defaultMethod: \"GET\",\n defaultExtra: { headers: {} },\n systemErrorStatus: 0,\n systemErrorExtra: { headers: {} },\n})\n .setQueryParamsMapper(stringifyQueryParams)\n .setFetcher(\n async ({\n url,\n endpoint,\n queryParams,\n request,\n headers,\n payload,\n adapter,\n adapterOptions,\n onError,\n onResponseEnd,\n onRequestEnd,\n createAbortListener,\n onResponseProgress,\n onRequestProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onSuccess,\n getAbortController,\n }) => {\n const { method } = request;\n\n const fullUrl = `${url}${endpoint}${queryParams}`;\n\n onBeforeRequest();\n\n const controller = getAbortController();\n const unmountListener =
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/adapter/adapter.ts"],"sourcesContent":["import { Adapter, stringifyQueryParams } from \"@hyper-fetch/core\";\nimport type { Method as AxiosMethods, AxiosRequestConfig } from \"axios\";\nimport axios, { AxiosHeaders } from \"axios\";\n\nimport type { AxiosExtra, RawAxiosHeaders } from \"./adapter.types\";\n\nexport type AxiosAdapterType = typeof AxiosAdapter;\n\n/** Pre-configured adapter that uses Axios as the underlying HTTP transport. Supports upload/download progress and abort. */\nexport const AxiosAdapter = new Adapter<\n Omit<AxiosRequestConfig, \"url\" | \"baseURL\" | \"method\" | \"onUploadProgress\" | \"onDownloadProgress\" | \"data\">,\n AxiosMethods,\n number,\n AxiosExtra\n>({\n name: \"axios-adapter\",\n defaultMethod: \"GET\",\n defaultExtra: { headers: {} },\n systemErrorStatus: 0,\n systemErrorExtra: { headers: {} },\n})\n .setQueryParamsMapper(stringifyQueryParams)\n .setFetcher(\n async ({\n url,\n endpoint,\n queryParams,\n request,\n headers,\n payload,\n adapter,\n adapterOptions,\n onError,\n onResponseEnd,\n onRequestEnd,\n createAbortListener,\n onResponseProgress,\n onRequestProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onSuccess,\n getAbortController,\n }) => {\n const { method } = request;\n\n const fullUrl = `${url}${endpoint}${queryParams}`;\n\n onBeforeRequest();\n\n const controller = getAbortController();\n // Reports the abort itself, so the request resolves with the abort error (and is never retried)\n const unmountListener = createAbortListener({\n status: 0,\n extra: { headers: {} },\n });\n\n if (controller?.signal.aborted) {\n unmountListener();\n return;\n }\n\n // The upload is over and the response has started once: with the first downloaded bytes, or with the\n // response itself when it has no body\n let hasResponseStarted = false;\n const startResponse = () => {\n if (hasResponseStarted) {\n return;\n }\n hasResponseStarted = true;\n onRequestEnd();\n onResponseStart();\n };\n\n onRequestStart();\n axios({\n ...adapterOptions,\n data: payload,\n method,\n url: fullUrl,\n signal: controller?.signal,\n headers: new AxiosHeaders(headers as RawAxiosHeaders),\n onUploadProgress: (progressEvent) => {\n onRequestProgress(progressEvent);\n },\n onDownloadProgress: (progressEvent) => {\n startResponse();\n onResponseProgress(progressEvent);\n },\n })\n .then((response) => {\n startResponse();\n onResponseEnd();\n onSuccess({ data: response.data, status: response.status, extra: { headers: response.headers } });\n })\n .catch((error) => {\n // The abort listener already resolved the request\n if (controller?.signal.aborted) {\n return;\n }\n if (error.response) {\n startResponse();\n }\n onError({\n error,\n status: error.response?.status || adapter.systemErrorStatus,\n extra: { headers: error.response?.headers ?? {} },\n });\n })\n .finally(() => {\n unmountListener();\n });\n },\n );\n"],"mappings":";;;;AASA,IAAa,eAAe,IAAI,QAK9B;CACA,MAAM;CACN,eAAe;CACf,cAAc,EAAE,SAAS,EAAE,EAAE;CAC7B,mBAAmB;CACnB,kBAAkB,EAAE,SAAS,EAAE,EAAE;CAClC,CAAC,CACC,qBAAqB,qBAAqB,CAC1C,WACC,OAAO,EACL,KACA,UACA,aACA,SACA,SACA,SACA,SACA,gBACA,SACA,eACA,cACA,qBACA,oBACA,mBACA,iBACA,iBACA,gBACA,WACA,yBACI;CACJ,MAAM,EAAE,WAAW;CAEnB,MAAM,UAAU,GAAG,MAAM,WAAW;AAEpC,kBAAiB;CAEjB,MAAM,aAAa,oBAAoB;CAEvC,MAAM,kBAAkB,oBAAoB;EAC1C,QAAQ;EACR,OAAO,EAAE,SAAS,EAAE,EAAE;EACvB,CAAC;AAEF,KAAI,YAAY,OAAO,SAAS;AAC9B,mBAAiB;AACjB;;CAKF,IAAI,qBAAqB;CACzB,MAAM,sBAAsB;AAC1B,MAAI,mBACF;AAEF,uBAAqB;AACrB,gBAAc;AACd,mBAAiB;;AAGnB,iBAAgB;AAChB,OAAM;EACJ,GAAG;EACH,MAAM;EACN;EACA,KAAK;EACL,QAAQ,YAAY;EACpB,SAAS,IAAI,aAAa,QAA2B;EACrD,mBAAmB,kBAAkB;AACnC,qBAAkB,cAAc;;EAElC,qBAAqB,kBAAkB;AACrC,kBAAe;AACf,sBAAmB,cAAc;;EAEpC,CAAC,CACC,MAAM,aAAa;AAClB,iBAAe;AACf,iBAAe;AACf,YAAU;GAAE,MAAM,SAAS;GAAM,QAAQ,SAAS;GAAQ,OAAO,EAAE,SAAS,SAAS,SAAS;GAAE,CAAC;GACjG,CACD,OAAO,UAAU;AAEhB,MAAI,YAAY,OAAO,QACrB;AAEF,MAAI,MAAM,SACR,gBAAe;AAEjB,UAAQ;GACN;GACA,QAAQ,MAAM,UAAU,UAAU,QAAQ;GAC1C,OAAO,EAAE,SAAS,MAAM,UAAU,WAAW,EAAE,EAAE;GAClD,CAAC;GACF,CACD,cAAc;AACb,mBAAiB;GACjB;EAEP"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hyper-fetch/axios",
|
|
3
|
-
"version": "9.6.
|
|
3
|
+
"version": "9.6.2",
|
|
4
4
|
"description": "Simple axios adapter for Hyper Fetch",
|
|
5
5
|
"author": "Maciej Pyrc <maciekpyrc@gmail.com>, Kacper Skawina <kacper.skawina@gmail.com>",
|
|
6
6
|
"homepage": "https://hyperfetch.bettertyped.com/",
|
package/src/adapter/adapter.ts
CHANGED
|
@@ -49,11 +49,28 @@ export const AxiosAdapter = new Adapter<
|
|
|
49
49
|
onBeforeRequest();
|
|
50
50
|
|
|
51
51
|
const controller = getAbortController();
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
52
|
+
// Reports the abort itself, so the request resolves with the abort error (and is never retried)
|
|
53
|
+
const unmountListener = createAbortListener({
|
|
54
|
+
status: 0,
|
|
55
|
+
extra: { headers: {} },
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
if (controller?.signal.aborted) {
|
|
59
|
+
unmountListener();
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// The upload is over and the response has started once: with the first downloaded bytes, or with the
|
|
64
|
+
// response itself when it has no body
|
|
65
|
+
let hasResponseStarted = false;
|
|
66
|
+
const startResponse = () => {
|
|
67
|
+
if (hasResponseStarted) {
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
hasResponseStarted = true;
|
|
71
|
+
onRequestEnd();
|
|
72
|
+
onResponseStart();
|
|
73
|
+
};
|
|
57
74
|
|
|
58
75
|
onRequestStart();
|
|
59
76
|
axios({
|
|
@@ -67,20 +84,27 @@ export const AxiosAdapter = new Adapter<
|
|
|
67
84
|
onRequestProgress(progressEvent);
|
|
68
85
|
},
|
|
69
86
|
onDownloadProgress: (progressEvent) => {
|
|
70
|
-
|
|
71
|
-
onResponseStart();
|
|
87
|
+
startResponse();
|
|
72
88
|
onResponseProgress(progressEvent);
|
|
73
89
|
},
|
|
74
90
|
})
|
|
75
91
|
.then((response) => {
|
|
76
|
-
|
|
92
|
+
startResponse();
|
|
77
93
|
onResponseEnd();
|
|
94
|
+
onSuccess({ data: response.data, status: response.status, extra: { headers: response.headers } });
|
|
78
95
|
})
|
|
79
96
|
.catch((error) => {
|
|
97
|
+
// The abort listener already resolved the request
|
|
98
|
+
if (controller?.signal.aborted) {
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (error.response) {
|
|
102
|
+
startResponse();
|
|
103
|
+
}
|
|
80
104
|
onError({
|
|
81
105
|
error,
|
|
82
106
|
status: error.response?.status || adapter.systemErrorStatus,
|
|
83
|
-
extra: { headers: error.response?.headers },
|
|
107
|
+
extra: { headers: error.response?.headers ?? {} },
|
|
84
108
|
});
|
|
85
109
|
})
|
|
86
110
|
.finally(() => {
|