dla
Version:
node.js data loader with caching and support of lists
76 lines • 2.95 kB
JavaScript
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 });
const utils_1 = require("./utils");
class MultiQuery {
constructor(loadFew, cache) {
this.touched = false;
this.sent = false;
this.promiseCache = {};
this.resolvers = {};
this.loadFew = loadFew;
this.cache = cache;
}
getOne(id) {
return __awaiter(this, void 0, void 0, function* () {
if (this.sent) {
throw new Error('Try to use MultiQuery after query has been sent');
}
if (!this.touched) {
this.touched = true;
Promise.resolve().then(() => {
process.nextTick(() => {
this.load();
});
});
}
if (!this.promiseCache[id]) {
this.promiseCache[id] = new Promise((resolve, reject) => {
this.resolvers[id] = [resolve, reject];
});
}
return this.promiseCache[id];
});
}
has(id) {
return id in this.promiseCache;
}
load() {
return __awaiter(this, void 0, void 0, function* () {
let res;
this.sent = true;
try {
if (this.cache) {
const now = Date.now();
res = utils_1.mapObjectValues(yield this.cache.mload(Object.keys(this.resolvers), (ids) => __awaiter(this, void 0, void 0, function* () {
return utils_1.mapObjectValues(yield this.loadFew(ids), (object) => ({
ts: now,
dt: object,
}));
}), { fast: true }), (object) => object.dt);
}
else {
res = yield this.loadFew(Object.keys(this.resolvers));
}
}
catch (err) {
for (const id of Object.keys(this.resolvers)) {
this.resolvers[id][1](err);
}
return;
}
for (const id of Object.keys(this.resolvers)) {
this.resolvers[id][0](res[id]);
}
});
}
}
exports.MultiQuery = MultiQuery;
//# sourceMappingURL=multi-query.js.map
;