-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfetch-timer.ts
More file actions
42 lines (37 loc) · 1.04 KB
/
fetch-timer.ts
File metadata and controls
42 lines (37 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { log } from '../logger/logger';
/**
* Sends AJAX request and wait for some time.
* If time is exceeded, cancel the request.
*
* @param {string} url — request endpoint
* @param {number} ms — maximum request time allowed
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function fetchTimer(url: string, ms: number): Promise<any> {
/**
* Using AbortController to cancel fetch request
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortController
*/
const controller = new AbortController();
const signal = controller.signal;
const fetchPromise = fetch(url, {
signal,
});
const timeoutId = setTimeout(() => {
controller.abort();
log('Request is too long, aborting...', 'log', url);
}, ms);
return fetchPromise
.then((response) => {
clearTimeout(timeoutId);
return response;
})
.catch((error) => {
clearTimeout(timeoutId);
/**
* Re-throw the error so it can be handled by the caller
*/
throw error;
});
}