forked from daniloc/airtable-api-proxy
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcache.js
71 lines (58 loc) · 1.96 KB
/
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* @file Common cache methods
* @author Avana Vana <[email protected]>
* @module cache
*/
const fs = require('fs');
/** @constant {number} cacheInterval - The duration, in seconds after which a cache file is considered stale (default: 300s = 5m) */
let cacheInterval = 60 * 5;
module.exports = {
/**
* Sets the cache interval (in integer seconds)
*
* @method setCacheInterval
* @param {number} interval - The number of seconds to set the cache interval to
*/
setCacheInterval: (interval) => {
cacheInterval = interval;
},
/**
* Uses a request's path to write a response as a file to the cache
*
* @method writeCacheWithPath
* @param {string} path - The request's URL, with query params
* @param {Object} data - The response, as a Javascript Object, from the request
*/
writeCacheWithPath: (path, data) => {
const queryPath = path.replace('?', '/');
`/${queryPath}`
.split('/')
.splice(0, `/${queryPath}`.split('/').length - 1)
.reduce((p, c) => {
p += `${c}/`;
!fs.existsSync(p) && fs.mkdirSync(p);
return p;
});
fs.writeFile(queryPath, JSON.stringify(data), (err) => {
if (err) throw new Error(err);
else console.log(`Cache write succeeded: ${path}`);
});
},
/**
* Uses a request's path to read a file from the cache if it exists or is still fresh
*
* @method writeCacheWithPath
* @param {string} path - The request's URL, with query params
* @returns {?Object} Returns cache JSON data as an object if it exists and is still fresh, else null
*/
readCacheWithPath: (path, stale = true) => {
if (stale) {
path = path.replace('?', '/');
if (fs.existsSync(path)) {
const cachedTime = fs.statSync(path).ctime;
stale = (new Date().getTime() - cachedTime) / 1000 > cacheInterval ? true : false;
}
}
return stale ? null : JSON.parse(fs.readFileSync(path, 'utf8'));
}
};