UNPKG

@ocap/indexdb-fs

Version:

OCAP indexdb adapter that uses file system as backend

78 lines (62 loc) 1.95 kB
/* eslint-disable no-underscore-dangle */ const path = require('path'); const { BaseIndex } = require('@ocap/indexdb'); const Lokijs = require('lokijs'); const FsAdapter = require('lokijs/src/loki-fs-structured-adapter'); const debug = require('debug')(require('../../package.json').name); class FsIndex extends BaseIndex { constructor(name, dataDir, uniqIndex) { super(name, uniqIndex); this.name = name; this.uniqIndex = uniqIndex; this.collection = null; const adapter = new FsAdapter(); const db = new Lokijs(path.join(dataDir, `${name}.db`), { adapter, autoload: true, autosave: true, autosaveInterval: 1000, autoloadCallback: () => { this.collection = db.getCollection(name); if (this.collection === null) { this.collection = db.addCollection(name, { unique: [this.primaryKey], clone: true }); } this.markReady(); }, }); this.db = db; } count(...args) { return this.collection.count(...args); } _insert(row) { const id = this.generatePrimaryKey(row); // Don't call this._get here cause _get may be overwritten const doc = FsIndex.prototype._get.call(this, id); if (doc) { return doc; } debug(`insert ${this.name}`, row); return this.collection.insert({ [this.primaryKey]: id, ...row }); } _get(key) { const id = this.generatePrimaryKey(key); return key ? this.collection.by(this.primaryKey, id) : null; } _update(key, updates) { const id = this.generatePrimaryKey(key); // Don't call this._get here cause _get may be overwritten const doc = FsIndex.prototype._get.call(this, id); if (!doc) { return null; } debug(`update ${this.name}`, { id, key, updates }); Object.assign(doc, updates); this.collection.update(doc); return doc; } _reset() { this.collection.removeWhere({}); } } module.exports = FsIndex;