This repository has been archived by the owner on Jan 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
CacheService.js
102 lines (90 loc) · 2.7 KB
/
CacheService.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
90
91
92
93
94
95
96
97
98
99
100
101
102
const fs = require('fs');
const path = require('path');
class CacheService {
constructor({clientId, clientSecret}) {
this._identifier = `${clientId}-${clientSecret}`;
this._cacheDir = path.join(__dirname, '../../.cache');
this._cacheMinutes = 10;
}
get() {
return this._getOrCreateFile().then(cache => {
const data = cache[this._identifier];
const now = new Date().getTime();
if (!data || !data.expires || data.expires < now) {
return {};
} else {
return data;
}
});
}
write(url) {
const expires = new Date().getTime() + this._cacheMinutes * 60 * 1000;
return this._getOrCreateFile().then(cache => {
cache[this._identifier] = {
expires,
url
};
return this._writeFile(JSON.stringify(cache)).then(() => undefined);
});
}
clear() {
return this._getOrCreateFile().then(cache => {
delete cache[this._identifier];
return this._writeFile(JSON.stringify(cache));
});
}
_getOrCreateFile() {
return this._checkFile().then(exists => {
if (!exists) {
return this._writeFile({flag: 'wx'}).then(() => {
return {};
});
} else {
return this._readFile().then(data => {
let cache = {};
try {
cache = JSON.parse(data)
} catch (err) {
}
return cache || {};
});
}
});
}
_checkFile() {
return new Promise(resolve => {
fs.access(this._cacheDir, fs.constants.F_OK | fs.constants.W_OK, err => {
if (err) {
if (err.code !== 'ENOENT') {
throw new Error(err);
}
resolve(false)
}
resolve(true);
});
})
}
_writeFile(contents) {
return new Promise((resolve, reject) => {
fs.writeFile(this._cacheDir, contents, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
})
}
_readFile() {
return new Promise((resolve, reject) => {
fs.readFile(this._cacheDir, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
})
}
}
module.exports = CacheService;