Update caching solution

This commit is contained in:
Henry
2019-01-30 10:12:22 +00:00
parent 47778c187d
commit af00264e92
5 changed files with 29 additions and 49 deletions

View File

@@ -15,28 +15,24 @@ module.exports = function(options = {}) {
ignoreQuery = false,
} = options;
const temporaryCache = new lru({
const pageCache = new lru({
maxAge: expire * 1000,
max: maxLength,
});
const persistentCache = new lru({
const routeCache = new lru({
maxAge: expire * 1000,
max: maxLength,
updateAgeOnGet: true,
});
options.app.context.cache = {
get: (key, persistent = false) => {
get: (key) => {
if (key) {
if (persistent) {
return persistentCache.get(key);
} else {
return temporaryCache.get(key);
}
return routeCache.get(key);
}
},
set: (key, value, maxAge, persistent = false) => {
set: (key, value, maxAge) => {
if (!value || value === 'undefined') {
value = '';
}
@@ -44,11 +40,7 @@ module.exports = function(options = {}) {
value = JSON.stringify(value);
}
if (key) {
if (persistent) {
return persistentCache.set(key, value, maxAge * 1000);
} else {
return temporaryCache.set(key, value, maxAge * 1000);
}
return routeCache.set(key, value, maxAge * 1000);
}
},
};
@@ -91,13 +83,13 @@ module.exports = function(options = {}) {
*/
async function getCache(ctx, key, tkey) {
let type;
const value = temporaryCache.get(key);
const value = pageCache.get(key);
let ok = false;
if (value) {
ctx.response.status = 200;
type = temporaryCache.get(tkey) || 'text/html';
type = pageCache.get(tkey) || 'text/html';
// can happen if user specified return_buffers: true in redis options
if (Buffer.isBuffer(type)) {
type = type.toString();
@@ -130,7 +122,7 @@ module.exports = function(options = {}) {
if (Buffer.byteLength(body) > maxLength) {
return;
}
temporaryCache.set(key, body);
pageCache.set(key, body);
await cacheType(ctx, tkey);
}
@@ -141,7 +133,7 @@ module.exports = function(options = {}) {
async function cacheType(ctx, tkey) {
const type = ctx.response.headers['content-type'];
if (type) {
temporaryCache.set(tkey, type);
pageCache.set(tkey, type);
}
}
};