-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathrequest-handler.js
89 lines (78 loc) · 2.27 KB
/
request-handler.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { getCore } from '../kibana-services';
let allow = true;
let aborts = [];
let currentid = 0;
const removeController = (id) => {
const index = aborts.findIndex(object => {
return object.id === id;
});
if (!id) {
return;
}
aborts.splice(index);
return;
}
export const disableRequests = () => {
allow = false;
aborts.forEach(item => {
item.controller.abort();
})
return;
}
export const initializeInterceptor = () => {
const core = getCore();
core.http.intercept({
responseError: (httpErrorResponse, controller) => {
if (
httpErrorResponse.response?.status === 401
) {
disableRequests();
setTimeout(() => window.location.reload(), 1000);
}
},
});
}
export const request = async (info = '') => {
if (!allow) {
return Promise.reject('Requests are disabled');
}
if (!info.method | !info.path) {
return Promise.reject("Missing parameters")
}
let { method, path, headers, data, timeout } = info;
const core = getCore();
const url = path.split('?')[0]
const query = Object.fromEntries([... new URLSearchParams(path.split('?')[1])])
const abort = new AbortController();
let options = {
method: method,
headers: headers,
query: query,
signal: abort.signal,
id: currentid
}
currentid++;
if (method !== 'GET') {
options = { ...options, body: JSON.stringify(data) }
}
if (allow) {
try {
aborts.push({ id: options.id, controller: abort })
if (timeout && timeout !== 0) {
const id = setTimeout(() => abort.abort(), timeout);
const requestData = await core.http.fetch(url, options);
clearTimeout(id);
removeController(options.id);
return Promise.resolve({ data: requestData, timeout: timeout });
}
else {
const requestData = await core.http.fetch(url, options);
removeController(options.id);
return Promise.resolve({ data: requestData });
}
}
catch (e) {
return Promise.reject(e);
}
}
}