UNPKG

dla

Version:

node.js data loader with caching and support of lists

103 lines 3.85 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 }); const cache_1 = require("./cache"); const multi_query_1 = require("./multi-query"); class Collection { constructor(options) { /** * Cache of objects requested during collection life */ this.promiseCache = {}; this.extractId = options.extractId; if (options.loadFew) { const loadFew = options.loadFew; this.loadFew = (ids) => __awaiter(this, void 0, void 0, function* () { const loaded = yield loadFew(ids); if (Array.isArray(loaded)) { const res = {}; for (const item of loaded) { res[this.extractId(item)] = item; } return res; } else { return loaded; } }); } else if (options.loadOne) { const loadOne = options.loadOne; this.loadFew = (ids) => __awaiter(this, void 0, void 0, function* () { const res = {}; (yield Promise.all(ids.map(loadOne))).forEach((obj, i) => { res[ids[i]] = obj; }); return res; }); } else { throw new Error('There should loadFew or loadOne method implemented'); } if (options.objectCache !== undefined) { this.objectCache = options.objectCache; } else if (options.cache) { this.objectCache = new cache_1.PrefixCache('o:', options.cache); } } getOne(id) { if (!this.promiseCache[id]) { if (!this.query || this.query.sent) { this.query = new multi_query_1.MultiQuery(this.loadFew, this.objectCache); } this.promiseCache[id] = this.query.getOne(id); } return this.promiseCache[id]; } getFewAsArray(ids) { return Promise.all(ids.map((id) => this.getOne(id))); } getFewAsMap(ids) { return __awaiter(this, void 0, void 0, function* () { const res = {}; (yield this.getFewAsArray(ids)).forEach((v, i) => { res[ids[i]] = v; }); return res; }); } clearCache(idS) { return __awaiter(this, void 0, void 0, function* () { if (Array.isArray(idS)) { if (this.objectCache) { yield this.objectCache.mremove(idS); } for (const id of idS) { delete this.promiseCache[id]; } if (this.query && idS.some((id) => this.query.has(id))) { this.query = null; } } else { if (this.objectCache) { yield this.objectCache.remove(idS); } delete this.promiseCache[idS]; if (this.query && this.query.has(idS)) { this.query = null; } } }); } } exports.Collection = Collection; //# sourceMappingURL=collection.js.map