Implement persistent cache

This commit is contained in:
Henry
2019-01-28 21:17:04 +00:00
parent 23d2039a73
commit 3b97b5fcb4
2 changed files with 33 additions and 19 deletions

View File

@@ -14,19 +14,28 @@ module.exports = function(options = {}) {
ignoreQuery = false,
} = options;
const memoryCache = new lru({
const temporaryCache = new lru({
maxAge: expire * 1000,
max: maxLength,
});
const persistentCache = new lru({
maxAge: expire * 1000,
max: maxLength,
updateAgeOnGet: true,
});
options.app.context.cache = {
get: (key) => {
get: (key, persistent) => {
if (key) {
return memoryCache.get(key);
if (persistent) {
return persistentCache.get(key);
} else {
return temporaryCache.get(key);
}
}
},
set: (key, value, maxAge) => {
set: (key, value, maxAge, persistent) => {
if (!value || value === 'undefined') {
value = '';
}
@@ -34,7 +43,11 @@ module.exports = function(options = {}) {
value = JSON.stringify(value);
}
if (key) {
memoryCache.set(key, value, maxAge * 1000);
if (persistent) {
return persistentCache.set(key, value, maxAge * 1000);
} else {
return temporaryCache.set(key, value, maxAge * 1000);
}
}
},
};
@@ -76,13 +89,14 @@ module.exports = function(options = {}) {
* getCache
*/
async function getCache(ctx, key, tkey) {
const value = memoryCache.get(key);
let type;
const value = temporaryCache.get(key);
let ok = false;
if (value) {
ctx.response.status = 200;
type = memoryCache.get(tkey) || 'text/html';
type = temporaryCache.get(tkey) || 'text/html';
// can happen if user specified return_buffers: true in redis options
if (Buffer.isBuffer(type)) {
type = type.toString();
@@ -115,7 +129,7 @@ module.exports = function(options = {}) {
if (Buffer.byteLength(body) > maxLength) {
return;
}
memoryCache.set(key, body);
temporaryCache.set(key, body);
await cacheType(ctx, tkey);
}
@@ -126,7 +140,7 @@ module.exports = function(options = {}) {
async function cacheType(ctx, tkey) {
const type = ctx.response.headers['content-type'];
if (type) {
memoryCache.set(tkey, type);
temporaryCache.set(tkey, type);
}
}
};