UNPKG

jinaga

Version:

Data management for web and mobile applications.

224 lines 10.5 kB
"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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ObserverImpl = void 0; const hash_1 = require("../fact/hash"); const description_1 = require("../specification/description"); const inverse_1 = require("../specification/inverse"); const storage_1 = require("../storage"); const encoding_1 = require("../util/encoding"); class ObserverImpl { constructor(factManager, given, specification, resultAdded) { this.factManager = factManager; this.given = given; this.specification = specification; this.listeners = []; this.removalsByTuple = {}; this.notifiedTuples = new Set(); this.addedHandlers = []; this.feeds = []; this.stopped = false; // Map the given facts to a tuple. const tuple = specification.given.reduce((tuple, label, index) => (Object.assign(Object.assign({}, tuple), { [label.name]: given[index] })), {}); this.givenHash = (0, hash_1.computeObjectHash)(tuple); // Add the initial handler. this.addedHandlers.push({ path: "", tupleHash: this.givenHash, handler: resultAdded }); // Identify the specification by its hash. const declarationString = (0, description_1.describeDeclaration)(given, specification.given); const specificationString = (0, description_1.describeSpecification)(specification, 0); const request = `${declarationString}\n${specificationString}`; this.specificationHash = (0, encoding_1.computeStringHash)(request); } start(keepAlive) { this.cachedPromise = new Promise((cacheResolve, _) => { this.loadedPromise = new Promise((loadResolve, loadReject) => __awaiter(this, void 0, void 0, function* () { try { const mruDate = yield this.factManager.getMruDate(this.specificationHash); if (mruDate === null) { // The data is not yet cached. cacheResolve(false); // Fetch from the server and then read from local storage. yield this.fetch(keepAlive); yield this.read(); loadResolve(); } else { // Read from local storage into the cache. yield this.read(); cacheResolve(true); // Then fetch from the server to update the cache. yield this.fetch(keepAlive); loadResolve(); } yield this.factManager.setMruDate(this.specificationHash, new Date()); } catch (e) { cacheResolve(false); loadReject(e); } })); }); } addSpecificationListeners() { const inverses = (0, inverse_1.invertSpecification)(this.specification); const listeners = inverses.map(inverse => this.factManager.addSpecificationListener(inverse.inverseSpecification, (results) => this.onResult(inverse, results))); this.listeners = listeners; } cached() { if (this.cachedPromise === undefined) { throw new Error("The observer has not been started."); } return this.cachedPromise; } loaded() { if (this.loadedPromise === undefined) { throw new Error("The observer has not been started."); } return this.loadedPromise; } stop() { this.stopped = true; for (const listener of this.listeners) { this.factManager.removeSpecificationListener(listener); } if (this.feeds.length > 0) { this.factManager.unsubscribe(this.feeds); } } fetch(keepAlive) { return __awaiter(this, void 0, void 0, function* () { if (keepAlive) { this.feeds = yield this.factManager.subscribe(this.given, this.specification); } else { yield this.factManager.fetch(this.given, this.specification); } }); } read() { return __awaiter(this, void 0, void 0, function* () { const projectedResults = yield this.factManager.read(this.given, this.specification); if (this.stopped) { // The observer was stopped before the read completed. return; } this.addSpecificationListeners(); const givenSubset = this.specification.given.map(g => g.name); yield this.notifyAdded(projectedResults, this.specification.projection, "", givenSubset); }); } onResult(inverse, results) { return __awaiter(this, void 0, void 0, function* () { // Filter out results that do not match the given. const matchingResults = results.filter(pr => this.givenHash === (0, storage_1.computeTupleSubsetHash)(pr.tuple, inverse.givenSubset)); if (matchingResults.length === 0) { return; } if (inverse.operation === "add") { return yield this.notifyAdded(matchingResults, inverse.inverseSpecification.projection, inverse.path, inverse.parentSubset); } else if (inverse.operation === "remove") { return yield this.notifyRemoved(inverse.resultSubset, matchingResults); } else { const _exhaustiveCheck = inverse.operation; throw new Error(`Inverse operation ${_exhaustiveCheck} not implemented.`); } }); } notifyAdded(projectedResults, projection, path, parentSubset) { return __awaiter(this, void 0, void 0, function* () { for (const pr of projectedResults) { const result = this.injectObservers(pr, projection, path); const parentTupleHash = (0, storage_1.computeTupleSubsetHash)(pr.tuple, parentSubset); const addedHandler = this.addedHandlers.find(h => h.tupleHash === parentTupleHash && h.path === path); const resultAdded = addedHandler === null || addedHandler === void 0 ? void 0 : addedHandler.handler; const tupleHash = (0, hash_1.computeObjectHash)(pr.tuple); // Don't call result added if we have already called it for this tuple. if (resultAdded && this.notifiedTuples.has(tupleHash) === false) { const promiseMaybe = resultAdded(result); this.notifiedTuples.add(tupleHash); if (promiseMaybe instanceof Promise) { const functionMaybe = yield promiseMaybe; if (functionMaybe instanceof Function) { this.removalsByTuple[tupleHash] = functionMaybe; } } else { const functionMaybe = promiseMaybe; if (functionMaybe instanceof Function) { this.removalsByTuple[tupleHash] = () => __awaiter(this, void 0, void 0, function* () { functionMaybe(); return Promise.resolve(); }); } } } // Recursively notify added for specification results. if (projection.type === "composite") { for (const component of projection.components) { if (component.type === "specification") { const childPath = path + "." + component.name; yield this.notifyAdded(pr.result[component.name], component.projection, childPath, Object.keys(pr.tuple)); } } } } }); } notifyRemoved(resultSubset, projectedResult) { return __awaiter(this, void 0, void 0, function* () { for (const pr of projectedResult) { const resultTupleHash = (0, storage_1.computeTupleSubsetHash)(pr.tuple, resultSubset); const removal = this.removalsByTuple[resultTupleHash]; if (removal !== undefined) { yield removal(); delete this.removalsByTuple[resultTupleHash]; // After the tuple is removed, it can be re-added. this.notifiedTuples.delete(resultTupleHash); } } }); } injectObservers(pr, projection, parentPath) { if (projection.type === "composite") { const composite = {}; for (const component of projection.components) { if (component.type === "specification") { const path = parentPath + "." + component.name; const observable = { onAdded: (handler) => { this.addedHandlers.push({ tupleHash: (0, hash_1.computeObjectHash)(pr.tuple), path: path, handler: handler }); } }; composite[component.name] = observable; } else { composite[component.name] = pr.result[component.name]; } } return composite; } else { return pr.result; } } } exports.ObserverImpl = ObserverImpl; //# sourceMappingURL=observer.js.map