UNPKG

dla

Version:

node.js data loader with caching and support of lists

95 lines 3.54 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); class Cache { has(key) { return __awaiter(this, void 0, void 0, function* () { return (yield this.get(key)) != null; }); } mhas(keys) { return __awaiter(this, void 0, void 0, function* () { const arr = yield Promise.all(keys.map((key) => this.has(key))); const res = {}; keys.forEach((id, i) => { res[id] = arr[i]; }); return res; }); } mget(keys) { return __awaiter(this, void 0, void 0, function* () { const res = {}; (yield Promise.all(keys.map((key) => this.get(key)))).forEach((val, i) => { if ((val) !== undefined) { res[keys[i]] = val; } }); return res; }); } mset(few, options) { return __awaiter(this, void 0, void 0, function* () { yield Promise.all(Object.keys(few).map((key) => this.set(key, few[key], options))); }); } setnx(key, value, options) { return __awaiter(this, void 0, void 0, function* () { if (!(yield this.has(key))) { yield this.set(key, value, options); } }); } msetnx(few, options) { return __awaiter(this, void 0, void 0, function* () { yield Promise.all(Object.keys(few).map((key) => this.setnx(key, few[key], options))); }); } mremove(keys) { return __awaiter(this, void 0, void 0, function* () { yield Promise.all(keys.map((key) => this.remove(key))); }); } load(key, loader, options = {}) { return __awaiter(this, void 0, void 0, function* () { let cached = yield this.get(key); if (cached === undefined) { cached = yield loader(); const setPromise = this.set(key, cached, options); if (!options.fast) { yield setPromise; } } return cached; }); } mload(keys, loader, options = {}) { return __awaiter(this, void 0, void 0, function* () { const cached = yield this.mget(keys); const restKeys = keys.filter((key) => cached[key] === undefined); if (!restKeys.length) { return cached; } const storaged = yield loader(restKeys); /*for(const key of restKeys) { if(!(key in storaged)) { storaged[key] = null; } }*/ const setPromise = this.mset(storaged, options); if (!options.fast) { yield setPromise; } return Object.assign({}, cached, storaged); }); } } exports.Cache = Cache; //# sourceMappingURL=cache.js.map