UNPKG

node-cache-redis

Version:

Simplistic node redis cache ready can scale with generic-pool support

302 lines (301 loc) 13.4 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var debug_1 = __importDefault(require("debug")); // @ts-ignore var is_json_1 = __importDefault(require("is-json")); var RedisConnectionPool_1 = __importDefault(require("./RedisConnectionPool")); var helpers_1 = require("./helpers"); var debug = debug_1.default('nodeRedisStore'); /** * RedisStore */ var RedisStore = /** @class */ (function (_super) { __extends(RedisStore, _super); /** * @constructor * @param options * @param options.name - Name your store * @param * @param * @param options.logger - Inject your custom logger * @param options.defaultTtlInS - Number of seconds to store by default */ function RedisStore(_a) { var name = _a.name, redisOptions = _a.redisOptions, poolOptions = _a.poolOptions, logger = _a.logger, defaultTtlInS = _a.defaultTtlInS; var _this = _super.call(this, { name: name || "redisStore-" + helpers_1.genRandomStr(), redisOptions: redisOptions, poolOptions: poolOptions, logger: helpers_1.createLogger(logger) }) || this; _this.deleteScriptPromise = null; _this.defaultTtlInS = helpers_1.validatedTtl(defaultTtlInS); return _this; } /** * Return the defaultTtlInS * @returns defaultTtlInS */ RedisStore.prototype.getDefaultTtlInS = function () { return this.defaultTtlInS; }; /** * Sets the defaultTtlInS * @param ttl * @returns defaultTtlInS */ RedisStore.prototype.setDefaultTtlInS = function (ttl) { this.defaultTtlInS = helpers_1.validatedTtl(ttl); return this.defaultTtlInS; }; /** * Unsets the defaultTtlInS * @param ttl * @returns true */ RedisStore.prototype.unsetDefaultTtlInS = function () { this.defaultTtlInS = undefined; return true; }; /** * Returns 'PONG' * * @param str - string passed * @returns 'PONG'/string passed */ RedisStore.prototype.ping = function (str) { return _super.prototype.sendCommand.call(this, 'ping', str ? [str] : []); }; /** * Returns value or null when the key is missing - See [redis get]{@link https://redis.io/commands/get} * @async * @param key - key for the value stored * @returns value or null when the key is missing */ RedisStore.prototype.get = function (key) { return __awaiter(this, void 0, void 0, function () { var result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, _super.prototype.sendCommand.call(this, 'get', [key])]; case 1: result = _a.sent(); try { result = JSON.parse(result); } catch (e) { // do nothing } return [2 /*return*/, result]; } }); }); }; /** * Returns 'OK' if successful * * @param key - key for the value stored * @param value - value to stored * @param ttlInSeconds - time to live in seconds * @returns 'OK' if successful */ RedisStore.prototype.set = function (key, value, ttlInSeconds) { var str = Array.isArray(value) || is_json_1.default(value, true) ? JSON.stringify(value) : value; var ttl = helpers_1.validatedTtl(ttlInSeconds, this.defaultTtlInS); if (ttl) { return _super.prototype.sendCommand.call(this, 'setex', [key, ttl, str]); } return _super.prototype.sendCommand.call(this, 'set', [key, str]); }; /** * Returns 'OK' if successful * @async * @param key - key for the value stored * @param value - value to stored * @param ttlInSeconds - time to live in seconds * @returns */ RedisStore.prototype.getset = function (key, value, ttlInSeconds) { return __awaiter(this, void 0, void 0, function () { var str, ttl, result; return __generator(this, function (_a) { switch (_a.label) { case 0: str = Array.isArray(value) || is_json_1.default(value, true) ? JSON.stringify(value) : value; ttl = helpers_1.validatedTtl(ttlInSeconds, this.defaultTtlInS); return [4 /*yield*/, _super.prototype.sendCommand.call(this, 'getset', [key, str])]; case 1: result = _a.sent(); try { result = JSON.parse(result); } catch (e) { // do nothing } if (!ttl) return [3 /*break*/, 3]; return [4 /*yield*/, _super.prototype.sendCommand.call(this, 'expire', [key, ttl])]; case 2: _a.sent(); _a.label = 3; case 3: return [2 /*return*/, result]; } }); }); }; /** * Returns the number of keys that were removed - See [redis del]{@link https://redis.io/commands/del} * * @param keys - list of keys to delete * @returns The number of keys that were removed. */ RedisStore.prototype.del = function (keys) { if (keys === void 0) { keys = []; } return _super.prototype.sendCommand.call(this, 'del', keys); }; /** * Returns 1 if the timeout was set/ 0 if key does not exist or the timeout could not be set - See [redis expire]{@link https://redis.io/commands/expire} * * @param {string} key - key to set expire * @param {number} ttlInSeconds - time to live in seconds * @returns 1 if the timeout was set successfully; if not 0 */ RedisStore.prototype.expire = function (key, ttlInSeconds) { var ttl = helpers_1.validatedTtl(ttlInSeconds); return _super.prototype.sendCommand.call(this, 'expire', [key, ttl]); }; /** * Returns TTL in seconds, or a negative value in order to signal an error - See [redis ttl]{@link https://redis.io/commands/ttl} * * @param key - list of keys to delete * @returns TTL in seconds, or a negative value in order to signal an error */ RedisStore.prototype.getTtl = function (key) { return _super.prototype.sendCommand.call(this, 'ttl', [key]); }; /** * Returns all keys matching pattern - See [redis keys]{@link https://redis.io/commands/keys} * * @param pattern - glob-style patterns/default '*' * @returns all keys matching pattern */ RedisStore.prototype.keys = function (pattern) { if (pattern === void 0) { pattern = '*'; } return _super.prototype.sendCommand.call(this, 'keys', [pattern]); }; /** * Deletes all keys matching pattern * * @param pattern - glob-style patterns/default '*' * @returns The number of keys that were removed. */ RedisStore.prototype.deleteAll = function (pattern) { if (pattern === void 0) { pattern = '*'; } debug('clearing redis keys: ', pattern); return this._executeDeleteAll(pattern); }; /** * Preloads delete all scripts into redis script cache (this script requires redis >= 4.0.0) * @returns sha1 hash of preloaded function * @private */ RedisStore.prototype._loadDeleteAllScript = function () { if (!this.deleteScriptPromise) { var deleteKeysScript = "\n local keys = {};\n local done = false;\n local cursor = \"0\";\n local deleted = 0;\n redis.replicate_commands();\n repeat\n local result = redis.call(\"SCAN\", cursor, \"match\", ARGV[1], \"count\", ARGV[2])\n cursor = result[1];\n keys = result[2];\n for i, key in ipairs(keys) do\n deleted = deleted + redis.call(\"UNLINK\", key);\n end\n if cursor == \"0\" then\n done = true;\n end\n until done\n return deleted;"; this.deleteScriptPromise = _super.prototype.sendCommand.call(this, 'SCRIPT', [ 'LOAD', deleteKeysScript ]); } return this.deleteScriptPromise; }; /** * Preloads and execute delete all script * @async * @param pattern - glob-style patterns/default '*' * @returns The number of keys that were removed. * @private */ RedisStore.prototype._executeDeleteAll = function (pattern) { return __awaiter(this, void 0, void 0, function () { var sha1, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this._loadDeleteAllScript()]; case 1: sha1 = _a.sent(); return [3 /*break*/, 3]; case 2: error_1 = _a.sent(); // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access if (error_1 && error_1.code === 'NOSCRIPT') { // We can get here only if server is restarted somehow and cache is deleted this.deleteScriptPromise = null; return [2 /*return*/, this._executeDeleteAll(pattern)]; } throw error_1; case 3: return [2 /*return*/, _super.prototype.sendCommand.call(this, 'EVALSHA', [sha1, 0, pattern, 1000])]; } }); }); }; return RedisStore; }(RedisConnectionPool_1.default)); exports.default = RedisStore;