@midwayjs/cache-manager
Version:
midway cache manager
80 lines • 2.88 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.memoryStore = void 0;
const LRUCache = require("lru-cache");
const cloneDeep = require("lodash.clonedeep");
function clone(object) {
if (typeof object === 'object' && object !== null) {
return cloneDeep(object);
}
return object;
}
/**
* Wrapper for lru-cache.
*/
function memoryStore(args) {
var _a;
const shouldCloneBeforeSet = (args === null || args === void 0 ? void 0 : args.shouldCloneBeforeSet) !== false; // clone by default
const isCacheable = (_a = args === null || args === void 0 ? void 0 : args.isCacheable) !== null && _a !== void 0 ? _a : (val => val !== undefined);
const lruOpts = {
ttlAutopurge: true,
...args,
max: (args === null || args === void 0 ? void 0 : args.max) || 500,
ttl: (args === null || args === void 0 ? void 0 : args.ttl) !== undefined ? args.ttl : 0,
};
const lruCache = new LRUCache(lruOpts);
return {
async del(key) {
lruCache.delete(key);
},
get: async (key) => lruCache.get(key),
keys: async () => [...lruCache.keys()],
mget: async (...args) => args.map(x => lruCache.get(x)),
async mset(args, ttl) {
const opt = { ttl: ttl !== undefined ? ttl : lruOpts.ttl };
for (const [key, value] of args) {
if (!isCacheable(value))
throw new Error(`no cacheable value ${JSON.stringify(value)}`);
if (shouldCloneBeforeSet)
lruCache.set(key, clone(value), opt);
else
lruCache.set(key, value, opt);
}
},
async mdel(...args) {
for (const key of args)
lruCache.delete(key);
},
async reset() {
lruCache.clear();
},
ttl: async (key) => lruCache.getRemainingTTL(key),
async set(key, value, opt) {
if (!isCacheable(value))
throw new Error(`no cacheable value ${JSON.stringify(value)}`);
if (shouldCloneBeforeSet)
value = clone(value);
const ttl = opt !== undefined ? opt : lruOpts.ttl;
lruCache.set(key, value, { ttl });
},
get calculatedSize() {
return lruCache.calculatedSize;
},
/**
* This method is not available in the caching modules.
*/
get size() {
return lruCache.size;
},
/**
* This method is not available in the caching modules.
*/
dump: () => lruCache.dump(),
/**
* This method is not available in the caching modules.
*/
load: (...args) => lruCache.load(...args),
};
}
exports.memoryStore = memoryStore;
//# sourceMappingURL=store.js.map
;