-
Notifications
You must be signed in to change notification settings - Fork 7
/
token-cache.js
55 lines (48 loc) · 1.3 KB
/
token-cache.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
const { Lock } = require('lock');
module.exports = (getToken, options) => {
const lock = Lock();
const getMaxAge =
options.getMaxAge ||
function getMaxAge() {
return options.maxAge || 0;
};
let cachedToken = null;
let cacheExpiration = null;
const cache = function getFromCache() {
if (cachedToken && cacheExpiration && cacheExpiration - Date.now() > 0) {
return Promise.resolve(cachedToken);
}
// Get a new token and prevent concurrent request.
return new Promise((resolve, reject) => {
lock('cache', (unlockFn) => {
const unlock = unlockFn();
// Token was already loaded by the previous lock.
if (
cachedToken &&
cacheExpiration &&
cacheExpiration - Date.now() > 0
) {
unlock();
return resolve(cachedToken);
}
// Get the token.
return getToken()
.then((token) => {
cachedToken = token;
cacheExpiration = Date.now() + getMaxAge(token);
unlock();
resolve(token);
})
.catch((err) => {
unlock();
reject(err);
});
});
});
};
cache.reset = function resetCache() {
cachedToken = null;
cacheExpiration = null;
};
return cache;
};