-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterceptor.js
More file actions
62 lines (55 loc) · 1.49 KB
/
interceptor.js
File metadata and controls
62 lines (55 loc) · 1.49 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
let interceptors = [];
function interceptor(fetch, ...args) {
const reversedInterceptors = interceptors.reduce(
(array, interceptor) => [interceptor].concat(array),
[]
);
let promise = Promise.resolve(args);
// Register request interceptors
reversedInterceptors.forEach(({ request, requestError }) => {
if (request || requestError) {
promise = promise.then((args) => request(...args), requestError);
}
});
// Register fetch call
promise = promise.then((args) => {
const request = new Request(...args);
return fetch(request)
.then((response) => {
response.request = request;
return response;
})
.catch((error) => {
error.request = request;
return Promise.reject(error);
});
});
// Register response interceptors
reversedInterceptors.forEach(({ response, responseError }) => {
if (response || responseError) {
promise = promise.then(response, responseError);
}
});
return promise;
}
module.exports = function attach(fetchLibrary) {
fetchLibrary = (function (fetch) {
return function (...args) {
return interceptor(fetch, ...args);
};
})(fetchLibrary);
return {
register: function (interceptor) {
interceptors.push(interceptor);
return () => {
const index = interceptors.indexOf(interceptor);
if (index >= 0) {
interceptors.splice(index, 1);
}
};
},
clear: function () {
interceptors = [];
},
};
};