UNPKG

@aspen.cloud/aspendb

Version:

Your unified, personal database to store data for many applications.

78 lines (77 loc) 2.6 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const pouchdb_1 = tslib_1.__importDefault(require("pouchdb")); pouchdb_1.default.plugin(require("pouchdb-find")); pouchdb_1.default.plugin(require("pouchdb-upsert")); const collate = require("pouchdb-collate"); const shortid_1 = tslib_1.__importDefault(require("shortid")); class AspenDB { constructor(db) { this.db = db; } app(appId) { return new AspenAppScope(this.db, appId); } } exports.default = AspenDB; class AspenAppScope { constructor(global, appId) { this.global = global; this.appId = appId; } async add(doc, type) { return this.global.putIfNotExists(this.addIdToDoc(doc, type)); } createFullId(id, docType) { const indexableAttributes = docType ? [this.appId, docType, id] : [this.appId, id]; // TODO Use custom fork of collate or make helper function return collate .toIndexableString(indexableAttributes) .replace(/\u0000/g, "\u0001"); } addIdToDoc(doc, type) { const docId = doc.id || shortid_1.default.generate(); const docType = type || doc.type; const fullId = this.createFullId(docId, docType); return Object.assign(Object.assign({}, doc), { _id: fullId }); } async addAll(docs) { return this.global.bulkDocs(docs.map(doc => this.addIdToDoc(doc))); } async all({ type, fullDocs = false, } = {}) { const indexArray = type ? [this.appId, type] : [this.appId]; const startkey = collate .toIndexableString(indexArray) .replace(/\u0000/g, "\u0001"); const endkey = collate .toIndexableString([...indexArray, "\ufff0"]) .replace(/\u0000/g, "\u0001"); const { rows } = await this.global.allDocs({ startkey, endkey, include_docs: fullDocs, }); return rows; } async find(query) { return this.global.find(query); } async putIndex(index) { return this.global.createIndex({ index: Object.assign(Object.assign({}, index), { ddoc: this.appId, type: "json" }), }); } async get(id) { return this.global.get(this.createFullId(id)); } async upsert(id, diffFunc) { return this.global.upsert(this.createFullId(id), diffFunc); } async putIfNotExits(doc) { return this.global.putIfNotExists(doc); } } exports.AspenAppScope = AspenAppScope;