UNPKG

redisess

Version:

Powerful redis session manager for NodeJS

48 lines (47 loc) 1.68 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RedisScript = void 0; const tslib_1 = require("tslib"); const putil_promisify_1 = tslib_1.__importDefault(require("putil-promisify")); class RedisScript { constructor(src, keys) { this._src = src; this._sha = ''; this._keys = keys || []; } async execute(client, ...args) { if (!this._sha) await this._loadScript(client); try { return await this._execute(client, ...args); } catch (err) { /* istanbul ignore next */ if (!String(err).includes('NOSCRIPT')) throw err; // Retry this._sha = ''; return await this._execute(client, ...args); } } async _execute(client, ...args) { await this._loadScript(client); const prms = [...this._keys]; const m = Math.max(this._keys.length, args.length); for (let i = 0; i < m; i++) { prms.push(this._keys[i] == null ? 'key' + (i + 1) : '' + this._keys[i]); } for (let i = 0; i < m; i++) { prms.push(args[i] == null ? '' : args[i]); } return !!(await putil_promisify_1.default.fromCallback(cb => client.evalsha(this._sha, m, ...prms, cb))); } async _loadScript(client) { const resp = await putil_promisify_1.default.fromCallback(cb => client.script('LOAD', this._src, cb)); /* istanbul ignore next */ if (!resp) throw new Error('Unable to load redis script in to redis cache'); this._sha = resp; } } exports.RedisScript = RedisScript;