UNPKG

layered-loader

Version:

Data loader with support for caching and fallback data sources

58 lines 1.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AbstractRedisCache = exports.DEFAULT_REDIS_CACHE_CONFIGURATION = void 0; exports.DEFAULT_REDIS_CACHE_CONFIGURATION = { json: false, prefix: 'layered-cache:', ttlInMsecs: 1000 * 60 * 10, separator: ':', }; class AbstractRedisCache { redis; config; constructor(redis, config) { this.redis = redis; // @ts-ignore this.config = { ...exports.DEFAULT_REDIS_CACHE_CONFIGURATION, ...config, }; } internalSet(resolvedKey, value) { const resolvedValue = value && this.config.json ? JSON.stringify(value) : value; if (this.config.ttlInMsecs) { return this.redis.set(resolvedKey, resolvedValue, 'PX', this.config.ttlInMsecs); } return this.redis.set(resolvedKey, resolvedValue); } postprocessResult(redisResult) { if (redisResult && this.config.json) { return JSON.parse(redisResult); } // Redis returns "null" for unknown values // ToDo We should create some fictional value for explicitly null values for redis if (redisResult === null) { return undefined; } return redisResult; } async clear() { const pattern = this.resolveCachePattern(); let cursor = '0'; do { const scanResults = await this.redis.scan(cursor, 'MATCH', pattern); cursor = scanResults[0]; if (scanResults[1].length > 0) { await this.redis.del(scanResults[1]); } } while (cursor !== '0'); } resolveKey(key) { return `${this.config.prefix}${this.config.separator}${key}`; } resolveCachePattern() { return `${this.config.prefix}${this.config.separator}*`; } } exports.AbstractRedisCache = AbstractRedisCache; //# sourceMappingURL=AbstractRedisCache.js.map