-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
86 lines (64 loc) · 1.59 KB
/
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
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
'use strict';
const path = require('path');
const Conf = require('conf');
const pkgUp = require('pkg-up');
const parentDir = path.dirname(module.parent.filename);
class CacheConf extends Conf {
constructor(options) {
const pkgPath = pkgUp.sync(parentDir);
options = Object.assign({
projectName: pkgPath && require(pkgPath).name // eslint-disable-line import/no-dynamic-require
}, options);
super(options);
this.version = options.version;
}
get(key, options) {
options = options || {};
if (options.ignoreMaxAge !== true && this.isExpired(key)) {
super.delete(key);
return;
}
const item = super.get(key);
return item && item.data;
}
set(key, val, opts) {
opts = opts || {};
if (typeof key === 'object') {
opts = val || {};
const timestamp = typeof opts.maxAge === 'number' ? Date.now() + opts.maxAge : undefined;
Object.keys(key).forEach(k => {
super.set(k, {
timestamp,
version: this.version,
data: key[k]
});
});
} else {
super.set(key, {
timestamp: typeof opts.maxAge === 'number' ? Date.now() + opts.maxAge : undefined,
version: this.version,
data: val
});
}
}
has(key) {
if (!super.has(key)) {
return false;
}
if (this.isExpired(key)) {
super.delete(key);
return false;
}
return true;
}
isExpired(key) {
const item = super.get(key);
if (!item) {
return false;
}
const invalidTimestamp = item.timestamp && item.timestamp < Date.now();
const invalidVersion = item.version !== this.version;
return Boolean(invalidTimestamp || invalidVersion);
}
}
module.exports = CacheConf;