unpkg/server/utils/createCache.js

33 lines
609 B
JavaScript
Raw Normal View History

2018-07-06 17:53:16 +00:00
const db = require("./cache");
2018-05-23 01:13:51 +00:00
/**
* A persistent cache for JSON values, using Redis.
*/
function createCache(keyPrefix) {
function createKey(key) {
2018-02-18 02:00:56 +00:00
return keyPrefix + "-" + key;
}
function set(key, value, expiry, callback) {
2018-02-18 02:00:56 +00:00
db.setex(createKey(key), expiry, JSON.stringify(value), callback);
}
function get(key, callback) {
2018-05-23 01:13:51 +00:00
db.get(createKey(key), (error, value) => {
2018-02-18 02:00:56 +00:00
callback(error, value && JSON.parse(value));
});
}
function del(key, callback) {
2018-02-18 02:00:56 +00:00
db.del(createKey(key), callback);
}
return {
set,
get,
del
2018-02-18 02:00:56 +00:00
};
}
2018-02-18 02:00:56 +00:00
module.exports = createCache;