Skip to content
This repository was archived by the owner on Mar 20, 2024. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 51 additions & 47 deletions lib/cache/index.js
Original file line number Diff line number Diff line change
@@ -1,65 +1,69 @@
const _ = require('lodash');
// @ts-check

const rejectAfterTimeout = (ms) => new Promise((_, reject) => setTimeout(reject, ms));
const _ = require("lodash");

const rejectAfterTimeout = (ms) =>
new Promise((_, reject) => setTimeout(reject, ms));

const serialize = (data) => {
return JSON.stringify({ data });
}
};

const deserialize = (str) => {
if (!str) {
return null;
}
return JSON.parse(str).data;
}

module.exports = (strapi, type = 'mem', opts = {}) => {

opts.max = opts.max || 500;
opts.maxAge = opts.maxAge || 60 * 60 * 1000;
const allowLogs = _.get(opts, 'logs', true);
const { cacheTimeout = 500, ...storeOpts } = opts;
};

const store = require(`./stores/${type}`)(strapi, storeOpts);
/**
*
* @param {any} strapi
* @param {import('../index').MiddlewareCacheConfig} options
* @param {import('../index').Logger} logger
*/
module.exports = (strapi, options, logger) => {
const store = require(`./stores/${options.type}`)(strapi, options);

return _.mapValues({
async get(key) {
return deserialize(await store.get(key));
},
async set(key, val, maxAge = opts.maxAge) {
return await store.set(key, serialize(val), maxAge);
return _.mapValues(
{
async get(key) {
return deserialize(await store.get(key));
},
async set(key, val, maxAge = options.maxAge) {
return await store.set(key, serialize(val), maxAge);
},
async peek(key) {
return deserialize(await store.peek(key));
},
async del(key) {
await store.del(key);
},
async keys() {
return await store.keys();
},
async reset() {
return await store.reset();
},
},
async peek(key) {
return deserialize(await store.peek(key));
},
async del(key) {
await store.del(key);
},
async keys() {
return await store.keys();
},
async reset() {
return await store.reset();
}
}, (fn) => async (...args) => {
try {
if (!store.ready) {
if (allowLogs) {
strapi.log.warn('[Cache] The store is not ready');
(fn) => async (...args) => {
try {
if (!store.ready) {
logger.warn("[Cache] The store is not ready");
return null;
}
return await Promise.race([
fn(...args),
rejectAfterTimeout(options.cacheTimeout),
]);
} catch (e) {
if (e) {
logger.warn("[Cache] There was an error with the store", e);
}
logger.warn("[Cache] The cache request timed out");

return null;
}
return await Promise.race([
fn(...args),
rejectAfterTimeout(cacheTimeout)
]);
} catch(e) {
if (e && allowLogs) {
strapi.log.warn('[Cache] There was an error with the store', e);
} else if (allowLogs) {
strapi.log.warn('[Cache] The cache request timed out');
}
return null;
}
});
);
};
Loading