UNPKG

@midwayjs/cache-manager

Version:
86 lines 3.52 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createRedisStore = void 0; const core_1 = require("@midwayjs/core"); const getVal = (value) => JSON.stringify(value) || '"undefined"'; function createRedisStore(instanceName) { return async (options, container) => { const { RedisServiceFactory } = (0, core_1.safeRequire)('@midwayjs/redis'); const redisServiceFactory = await container.getAsync(RedisServiceFactory); const redisInstance = redisServiceFactory.get(instanceName); return createStore(redisInstance, options); }; } exports.createRedisStore = createRedisStore; function createStore(redisCache, options) { const isCacheable = (options === null || options === void 0 ? void 0 : options.isCacheable) || (value => value !== undefined && value !== null); const keys = (pattern) => redisCache.keys(pattern); return { async get(key) { const val = await redisCache.get(key); if (val === undefined || val === null) return undefined; else { try { return JSON.parse(val); } catch (e) { return val; } } }, async set(key, value, ttl) { if (!isCacheable(value)) throw new core_1.MidwayCommonError(`"${value}" is not a cacheable value`); const t = ttl === undefined ? options === null || options === void 0 ? void 0 : options.ttl : ttl; if (t !== undefined && t !== 0) await redisCache.set(key, getVal(value), 'PX', t); else await redisCache.set(key, getVal(value)); }, async mset(args, ttl) { const t = ttl === undefined ? options === null || options === void 0 ? void 0 : options.ttl : ttl; if (t !== undefined && t !== 0) { const multi = redisCache.multi(); for (const [key, value] of args) { if (!isCacheable(value)) throw new core_1.MidwayCommonError(`"${getVal(value)}" is not a cacheable value`); multi.set(key, getVal(value), 'PX', t); } await multi.exec(); } else await redisCache.mset(args.flatMap(([key, value]) => { if (!isCacheable(value)) throw new Error(`"${getVal(value)}" is not a cacheable value`); return [key, getVal(value)]; })); }, mget: (...args) => redisCache.mget(args).then(x => x.map(x => { if (x === null || x === undefined) { return undefined; } else { try { return JSON.parse(x); } catch (_a) { return x; } } })), async mdel(...args) { await redisCache.del(args); }, async del(key) { await redisCache.del(key); }, ttl: async (key) => redisCache.pttl(key), keys: (pattern = '*') => keys(pattern), reset: () => { throw new core_1.MidwayCommonError('flushdb() is too dangerous, if necessary, please use redisServiceFactory.get(client) to get the instance and call it manually.'); }, isCacheable, }; } //# sourceMappingURL=store.js.map