@naturalcycles/db-lib
Version:
Lowest Common Denominator API to supported Databases
52 lines (51 loc) • 1.84 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.InMemoryKeyValueDB = void 0;
const node_stream_1 = require("node:stream");
const commonKeyValueDB_1 = require("../../kv/commonKeyValueDB");
class InMemoryKeyValueDB {
constructor(cfg = {}) {
this.cfg = cfg;
this.support = {
...commonKeyValueDB_1.commonKeyValueDBFullSupport,
};
// data[table][id] => any (can be Buffer, or number)
this.data = {};
}
async ping() { }
async createTable(_table, _opt) { }
async deleteByIds(table, ids) {
this.data[table] ||= {};
ids.forEach(id => delete this.data[table][id]);
}
async getByIds(table, ids) {
this.data[table] ||= {};
return ids.map(id => [id, this.data[table][id]]).filter(e => e[1]);
}
async saveBatch(table, entries) {
this.data[table] ||= {};
entries.forEach(([id, v]) => (this.data[table][id] = v));
}
streamIds(table, limit) {
return node_stream_1.Readable.from(Object.keys(this.data[table] || {}).slice(0, limit));
}
streamValues(table, limit) {
return node_stream_1.Readable.from(Object.values(this.data[table] || {}).slice(0, limit));
}
streamEntries(table, limit) {
return node_stream_1.Readable.from(Object.entries(this.data[table] || {}).slice(0, limit));
}
async count(table) {
this.data[table] ||= {};
return Object.keys(this.data[table]).length;
}
async incrementBatch(table, entries) {
this.data[table] ||= {};
return entries.map(([id, by]) => {
const newValue = Number(this.data[table][id] || 0) + by;
this.data[table][id] = newValue;
return [id, newValue];
});
}
}
exports.InMemoryKeyValueDB = InMemoryKeyValueDB;