-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstore.js
90 lines (82 loc) · 2.29 KB
/
store.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
const os = require('os');
const path = require('path');
const bootcdn = require('./bootcdn');
const cacheManager = require('cache-manager');
const cacheFs = require('cache-manager-fs');
let cache = null;
const init = function init() {
if (cache !== null) return;
return new Promise(r => {
cache = cacheManager.caching({
store: cacheFs,
options: {
ttl: 3600 * 24,
maxsize: 1024 * 2048,
path: path.join(os.tmpdir(), 'bootcdn-cli'),
preventfill: false,
fillcallback: r
}
});
});
};
const refresh = function refresh() {
if (cache === null) init();
return new Promise((resolve, reject) => {
cache.reset(err => {
if (err) reject(err);
resolve();
});
});
};
function yieldObj(map) {
return Array.from(map.entries()).map(([k, v]) => [k, v]);
}
function yieldArray(set) {
return Array.from(set.values());
}
function fetchFromCache(key, fetchAsync, type) {
if (cache === null) init();
return new Promise((resolve) => {
cache.get(key, (err, res) => {
// Caching error doesn't matter
cacheHit = res !== null;
switch (type) {
case 'map':
resolve(new Map(res));
break;
case 'set':
resolve(new Set(res));
break;
default:
resolve(res);
break;
}
});
})
.then(res => cacheHit ? res : fetchAsync())
.then(res => new Promise((resolve, reject) => {
if (!cacheHit && res !== null) {
let storeObj;
switch (type) {
case 'map':
storeObj = yieldObj(res);
break;
case 'set':
storeObj = yieldArray(res);
break;
default:
storeObj = res;
break;
}
cache.set(key, storeObj, () => resolve(res));
} else {
resolve(res);
}
}));
}
module.exports = {
init,
refresh,
fetchAllLibraries: () => fetchFromCache('bootcdn.alllibs', bootcdn.fetchAllLibraries, 'map'),
fetchLibrary: lib => fetchFromCache(lib, () => bootcdn.fetchLibrary(lib), 'json')
};