ioredis-cache
Version:
A promise-based cache package for Nodejs using IORedis
504 lines (503 loc) • 22.8 kB
JavaScript
"use strict";
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 __asyncValues = (this && this.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var ioredis_1 = __importDefault(require("ioredis"));
var NOT_FOUND_VALUE = undefined;
var isRedis = function (obj) {
if (obj == null) {
return false;
}
return [
"set",
"get",
"setex",
"mget",
"pipeline",
"del",
"hset",
"get",
"hdel",
].every(function (name) { return typeof obj[name] === "function"; });
};
var Cache = /** @class */ (function () {
function Cache(options) {
var _this = this;
this.parser = JSON;
this._buildSetParams = function (valueMap) {
var params = [];
for (var _i = 0, _a = Object.entries(valueMap); _i < _a.length; _i++) {
var _b = _a[_i], key = _b[0], value = _b[1];
params.push(key, _this.parser.stringify(value));
}
return params;
};
var config = (isRedis(options) ? { redis: options } : options);
if (isRedis(config.redis)) {
this.redis = config.redis;
}
else {
this.redis = new ioredis_1.default(config.redis);
}
this.prefix = this.redis.options.keyPrefix || "";
if (config.parser !== undefined) {
this.parser = config.parser;
}
}
Cache.bindAll = function (target) {
for (var _i = 0, _a = Object.getOwnPropertyNames(Cache.prototype); _i < _a.length; _i++) {
var name = _a[_i];
if (name === "constructor") {
continue;
}
target[name] = target[name].bind(target);
}
return target;
};
Cache.prototype.cache = function (key, fn, ttl) {
return __awaiter(this, void 0, void 0, function () {
var value;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getCache(key)];
case 1:
value = _a.sent();
if (value !== NOT_FOUND_VALUE) {
return [2 /*return*/, value];
}
return [4 /*yield*/, fn()];
case 2:
value = _a.sent();
return [4 /*yield*/, this.setCache(key, value, ttl)];
case 3:
_a.sent();
return [2 /*return*/, value];
}
});
});
};
Cache.prototype.getCache = function (key) {
return __awaiter(this, void 0, void 0, function () {
var data;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.redis.get(key)];
case 1:
data = _a.sent();
return [2 /*return*/, data ? this.parser.parse(data) : NOT_FOUND_VALUE];
}
});
});
};
Cache.prototype.setCache = function (key, value, ttl) {
return __awaiter(this, void 0, void 0, function () {
var data;
return __generator(this, function (_a) {
data = this.parser.stringify(value);
return [2 /*return*/, ttl !== undefined
? this.redis.setex(key, ttl, data)
: this.redis.set(key, data)];
});
});
};
Cache.prototype.manyCache = function (keys, fn, prefix, ttl) {
if (prefix === void 0) { prefix = ""; }
return __awaiter(this, void 0, void 0, function () {
var fullKeys, cachedValues, uncachedKeys, i, uncachedValues_1, uncachedValueMap, fullKeyUncachedValueMap, i;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
fullKeys = keys.map(function (key) { return "" + prefix + key; });
return [4 /*yield*/, this.getManyCache(fullKeys)];
case 1:
cachedValues = _a.sent();
uncachedKeys = [];
for (i = 0; i < cachedValues.length; ++i) {
if (cachedValues[i] === NOT_FOUND_VALUE) {
uncachedKeys.push(keys[i]);
}
}
if (!uncachedKeys.length) return [3 /*break*/, 4];
return [4 /*yield*/, fn(uncachedKeys)];
case 2:
uncachedValues_1 = _a.sent();
uncachedValueMap = Array.isArray(uncachedValues_1)
? uncachedKeys.reduce(function (c, key, idx) {
var _a;
return Object.assign(c, (_a = {}, _a[key] = uncachedValues_1[idx], _a));
}, {})
: uncachedValues_1;
fullKeyUncachedValueMap = Object.entries(uncachedValueMap).reduce(function (c, _a) {
var _b;
var key = _a[0], value = _a[1];
return Object.assign(c, (_b = {}, _b["" + prefix + key] = value, _b));
}, {});
return [4 /*yield*/, this.setManyCache(fullKeyUncachedValueMap, ttl)];
case 3:
_a.sent();
for (i = 0; i < cachedValues.length; ++i) {
if (cachedValues[i] === NOT_FOUND_VALUE) {
cachedValues[i] = uncachedValueMap[keys[i]];
}
}
_a.label = 4;
case 4: return [2 /*return*/, cachedValues];
}
});
});
};
Cache.prototype.getManyCache = function (keys) {
return __awaiter(this, void 0, void 0, function () {
var data;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (keys.length <= 0) {
return [2 /*return*/, []];
}
return [4 /*yield*/, this.redis.mget(keys)];
case 1:
data = _a.sent();
return [2 /*return*/, data.map(function (e) {
return !e ? NOT_FOUND_VALUE : _this.parser.parse(e);
})];
}
});
});
};
Cache.prototype.setManyCache = function (valueMap, ttl) {
return __awaiter(this, void 0, void 0, function () {
var keys, params, pipeline, _i, keys_1, key;
return __generator(this, function (_a) {
keys = Object.keys(valueMap);
if (keys.length <= 0) {
return [2 /*return*/, []];
}
params = this._buildSetParams(valueMap);
if (ttl === undefined) {
return [2 /*return*/, this.redis.mset(params)];
}
pipeline = this.redis.pipeline();
pipeline.mset(params);
for (_i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
key = keys_1[_i];
pipeline.expire(key, ttl);
}
return [2 /*return*/, pipeline.exec()];
});
});
};
Cache.prototype.deleteCache = function () {
var keys = [];
for (var _i = 0; _i < arguments.length; _i++) {
keys[_i] = arguments[_i];
}
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
return [2 /*return*/, (_a = this.redis).del.apply(_a, keys)];
});
});
};
Cache.prototype.deletePattern = function (pattern, batch) {
var e_1, _a;
if (batch === void 0) { batch = 100; }
return __awaiter(this, void 0, void 0, function () {
var jobs, length, pipeline, _b, _c, keys, _i, keys_2, key, e_1_1;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
jobs = [];
length = this.prefix.length;
pipeline = this.redis.pipeline();
_d.label = 1;
case 1:
_d.trys.push([1, 6, 7, 12]);
_b = __asyncValues(this.redis.scanStream({
match: "" + this.prefix + pattern,
count: batch,
}));
_d.label = 2;
case 2: return [4 /*yield*/, _b.next()];
case 3:
if (!(_c = _d.sent(), !_c.done)) return [3 /*break*/, 5];
keys = _c.value;
for (_i = 0, keys_2 = keys; _i < keys_2.length; _i++) {
key = keys_2[_i];
pipeline.del(key.substring(length));
}
if (pipeline.length >= batch) {
jobs.push(pipeline.exec());
pipeline = this.redis.pipeline();
}
_d.label = 4;
case 4: return [3 /*break*/, 2];
case 5: return [3 /*break*/, 12];
case 6:
e_1_1 = _d.sent();
e_1 = { error: e_1_1 };
return [3 /*break*/, 12];
case 7:
_d.trys.push([7, , 10, 11]);
if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 9];
return [4 /*yield*/, _a.call(_b)];
case 8:
_d.sent();
_d.label = 9;
case 9: return [3 /*break*/, 11];
case 10:
if (e_1) throw e_1.error;
return [7 /*endfinally*/];
case 11: return [7 /*endfinally*/];
case 12:
jobs.push(pipeline.exec());
return [4 /*yield*/, Promise.all(jobs)];
case 13:
_d.sent();
return [2 /*return*/];
}
});
});
};
Cache.prototype.hashCache = function (key, id, fn) {
return __awaiter(this, void 0, void 0, function () {
var value;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getHashCache(key, id)];
case 1:
value = _a.sent();
if (value !== NOT_FOUND_VALUE) {
return [2 /*return*/, value];
}
return [4 /*yield*/, fn()];
case 2:
value = _a.sent();
return [4 /*yield*/, this.setHashCache(key, id, value)];
case 3:
_a.sent();
return [2 /*return*/, value];
}
});
});
};
Cache.prototype.getHashCache = function (key, id) {
return __awaiter(this, void 0, void 0, function () {
var data;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.redis.hget(key, id)];
case 1:
data = _a.sent();
return [2 /*return*/, data ? this.parser.parse(data) : NOT_FOUND_VALUE];
}
});
});
};
Cache.prototype.setHashCache = function (key, id, value) {
return __awaiter(this, void 0, void 0, function () {
var data;
return __generator(this, function (_a) {
data = this.parser.stringify(value);
return [2 /*return*/, this.redis.hset(key, id, data)];
});
});
};
Cache.prototype.hashManyCache = function (key, ids, fn) {
return __awaiter(this, void 0, void 0, function () {
var cachedValues, uncachedIds, i, uncachedValues_2, uncachedValueMap, i;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getHashManyCache(key, ids)];
case 1:
cachedValues = _a.sent();
uncachedIds = [];
for (i = 0; i < cachedValues.length; ++i) {
if (cachedValues[i] === NOT_FOUND_VALUE) {
uncachedIds.push(ids[i]);
}
}
if (!uncachedIds.length) return [3 /*break*/, 4];
return [4 /*yield*/, fn(uncachedIds)];
case 2:
uncachedValues_2 = _a.sent();
uncachedValueMap = Array.isArray(uncachedValues_2)
? uncachedIds.reduce(function (c, key, idx) {
var _a;
return Object.assign(c, (_a = {}, _a[key] = uncachedValues_2[idx], _a));
}, {})
: uncachedValues_2;
return [4 /*yield*/, this.setHashManyCache(key, uncachedValueMap)];
case 3:
_a.sent();
for (i = 0; i < cachedValues.length; ++i) {
if (cachedValues[i] === NOT_FOUND_VALUE) {
cachedValues[i] = uncachedValueMap[ids[i]];
}
}
_a.label = 4;
case 4: return [2 /*return*/, cachedValues];
}
});
});
};
Cache.prototype.getHashManyCache = function (key, ids) {
return __awaiter(this, void 0, void 0, function () {
var data;
var _a;
var _this = this;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (ids.length <= 0) {
return [2 /*return*/, []];
}
return [4 /*yield*/, (_a = this.redis).hmget.apply(_a, __spreadArrays([key], ids))];
case 1:
data = _b.sent();
return [2 /*return*/, data.map(function (e) {
return !e ? NOT_FOUND_VALUE : _this.parser.parse(e);
})];
}
});
});
};
Cache.prototype.setHashManyCache = function (key, valueMap) {
return __awaiter(this, void 0, void 0, function () {
var params;
return __generator(this, function (_a) {
if (Object.keys(valueMap).length <= 0) {
return [2 /*return*/, []];
}
params = this._buildSetParams(valueMap);
return [2 /*return*/, this.redis.hmset(key, params)];
});
});
};
Cache.prototype.deleteHashCache = function (key) {
var ids = [];
for (var _i = 1; _i < arguments.length; _i++) {
ids[_i - 1] = arguments[_i];
}
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
return [2 /*return*/, (_a = this.redis).hdel.apply(_a, __spreadArrays([key], ids))];
});
});
};
Cache.prototype.acquire = function (key, amount, fn, float) {
if (float === void 0) { float = false; }
return __awaiter(this, void 0, void 0, function () {
var change, parser, current, result, error_1, n;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
change = (float ? this.redis.incrbyfloat : this.redis.incrby);
parser = float ? parseFloat : parseInt;
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 6]);
return [4 /*yield*/, change.call(this.redis, key, amount)];
case 2:
current = _a.sent();
return [4 /*yield*/, fn(parser(current))];
case 3:
result = _a.sent();
return [2 /*return*/, result];
case 4:
error_1 = _a.sent();
return [4 /*yield*/, change.call(this.redis, key, -amount)];
case 5:
n = _a.sent();
throw error_1;
case 6: return [2 /*return*/];
}
});
});
};
Cache.prototype.hashAcquire = function (key, id, amount, fn, float) {
if (float === void 0) { float = false; }
return __awaiter(this, void 0, void 0, function () {
var change, parser, current, result, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
change = (float ? this.redis.hincrbyfloat : this.redis.hincrby);
parser = float ? parseFloat : parseInt;
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 6]);
return [4 /*yield*/, change.call(this.redis, key, id, amount)];
case 2:
current = _a.sent();
return [4 /*yield*/, fn(parser(current))];
case 3:
result = _a.sent();
return [2 /*return*/, result];
case 4:
error_2 = _a.sent();
return [4 /*yield*/, change.call(this.redis, key, id, -amount)];
case 5:
_a.sent();
throw error_2;
case 6: return [2 /*return*/];
}
});
});
};
return Cache;
}());
exports.default = Cache;