UNPKG

@mkeen/rxcouch

Version:

Real Time RxJs Based CouchDB Client

81 lines 3.17 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CouchDBDocumentCollection = void 0; var rxjs_1 = require("rxjs"); var js_sha256_1 = require("js-sha256"); var _ = require("lodash"); var CouchDBDocumentCollection = /** @class */ (function () { function CouchDBDocumentCollection() { this.ids = new rxjs_1.BehaviorSubject([]); this.documents = {}; this.snapshots = {}; } CouchDBDocumentCollection.prototype.changed = function (document) { // todo, dont let undefined get this far if (!document) { return false; } var docCopy = JSON.parse(JSON.stringify(document)); if (this.isPreDocument(docCopy)) { return true; } delete docCopy._rev; var snapshot = this.snapshots[docCopy._id]; if (snapshot === undefined) { return true; } return snapshot !== js_sha256_1.sha256(JSON.stringify(docCopy)); }; CouchDBDocumentCollection.prototype.snapshot = function (document) { var docCopy = JSON.parse(JSON.stringify(document)); delete docCopy._rev; return this.snapshots[docCopy._id] = js_sha256_1.sha256(JSON.stringify(docCopy)); }; CouchDBDocumentCollection.prototype.clear = function () { this.documents = {}; this.ids.next([]); }; CouchDBDocumentCollection.prototype.doc = function (document) { if (typeof (document) === 'string') { return this.documents[document]; } if (this.isKnownDocument(document._id)) { if (this.changed(document)) { this.snapshot(document); this.documents[document._id].next(document); } return this.documents[document._id]; } else { this.add(document); this.snapshot(document); } return this.documents[document._id]; }; CouchDBDocumentCollection.prototype.isKnownDocument = function (document_id) { return this.documents[document_id] !== undefined; }; CouchDBDocumentCollection.prototype.isStoredCouchDBDocument = function (entity) { return '_id' in entity && '_rev' in entity; }; CouchDBDocumentCollection.prototype.isPreDocument = function (item) { return !this.isStoredCouchDBDocument(item); }; CouchDBDocumentCollection.prototype.add = function (document) { if (!this.documents[document._id]) { this.documents[document._id] = new rxjs_1.BehaviorSubject(document); this.ids.next(_.sortBy(// todo: I don't think this sort is needed _.union(this.ids.value, [document._id]))); } }; CouchDBDocumentCollection.prototype.remove = function (documentId) { var index = this.ids.value.indexOf(documentId); if (index !== -1) { this.ids.next(this.ids.value.splice(index, 1)); delete this.documents[documentId]; } }; return CouchDBDocumentCollection; }()); exports.CouchDBDocumentCollection = CouchDBDocumentCollection; //# sourceMappingURL=couchdbdocumentcollection.js.map