-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
41 lines (34 loc) · 1.28 KB
/
index.js
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
export class HttpError extends Error {
constructor(response) {
const status = `${response.status} ${response.statusText}`.trim();
const reason = status ? `status code ${status}` : 'an unknown error';
super(`Request failed with ${reason}: ${response.url}`);
Error.captureStackTrace?.(this, this.constructor);
this.name = 'HttpError';
this.code = 'ERR_HTTP_RESPONSE_NOT_OK';
this.response = response;
}
}
export async function throwIfHttpError(responseOrPromise) {
if (!(responseOrPromise instanceof Response)) {
responseOrPromise = await responseOrPromise;
}
if (!responseOrPromise.ok) {
throw new HttpError(responseOrPromise);
}
return responseOrPromise;
}
export function withHttpError(fetchFunction) {
return async (urlOrRequest, options = {}) => {
const response = await fetchFunction(urlOrRequest, options);
return throwIfHttpError(response);
};
}
export function withTimeout(fetchFunction, timeout) {
return async (urlOrRequest, options = {}) => {
const providedSignal = options.signal ?? (urlOrRequest instanceof Request && urlOrRequest.signal);
const timeoutSignal = AbortSignal.timeout(timeout);
const signal = providedSignal ? AbortSignal.any([providedSignal, timeoutSignal]) : timeoutSignal;
return fetchFunction(urlOrRequest, {...options, signal});
};
}