@ocap/indexdb-memory
Version:
OCAP indexdb adapter that uses memory as backend, just for test purpose
54 lines (40 loc) • 1.32 kB
JavaScript
/* eslint-disable no-underscore-dangle */
const { BaseIndex } = require('@ocap/indexdb');
const Lokijs = require('lokijs');
const debug = require('debug')(require('../../package.json').name);
const db = new Lokijs('ocap-memory-indexdb.db');
class MemoryIndex extends BaseIndex {
constructor(name, uniqIndex) {
super(name, uniqIndex);
this.uniqIndex = uniqIndex;
this.collection = db.addCollection(name, { unique: [this.primaryKey], clone: true });
this.markReady();
}
count(...args) {
return this.collection.count(...args);
}
_insert(row) {
debug(`insert ${this.name}`, row);
const id = this.generatePrimaryKey(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 = MemoryIndex.prototype._get.call(this, id);
if (!doc) {
throw new Error(`${this.name} does not exists: ${key}`);
}
Object.assign(doc, updates);
this.collection.update(doc);
return doc;
}
_reset() {
this.collection.removeWhere({});
}
}
module.exports = MemoryIndex;