redisess
Version:
Powerful redis session manager for NodeJS
43 lines (42 loc) • 1.44 kB
JavaScript
import promisify from 'putil-promisify';
export 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 promisify.fromCallback(cb => client.evalsha(this._sha, m, ...prms, cb)));
}
async _loadScript(client) {
const resp = await promisify.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;
}
}