-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
33 lines (27 loc) · 805 Bytes
/
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
const tokenCache = require('./token-cache');
function getToken(options) {
if (options.token) {
return Promise.resolve(options.token);
}
const token = options.getToken();
if (typeof token !== 'object' || !token.then) {
return Promise.resolve(token);
}
return token;
}
module.exports = function tokenInterceptor(options) {
const header = options.header || 'Authorization';
const headerFormatter =
options.headerFormatter ||
function defaultHeaderFormatter(token) {
return `Bearer ${token}`;
};
return function interceptRequest(config) {
const requestConfig = config;
return getToken(options).then((token) => {
requestConfig.headers[header] = headerFormatter(token);
return config;
});
};
};
module.exports.tokenCache = tokenCache;