@naturalcycles/db-lib
Version:
Lowest Common Denominator API to supported Databases
49 lines (48 loc) • 1.61 kB
JavaScript
import { Readable } from 'node:stream';
import { commonKeyValueDBFullSupport } from '../kv/commonKeyValueDB.js';
export class InMemoryKeyValueDB {
cfg;
constructor(cfg = {}) {
this.cfg = cfg;
}
support = {
...commonKeyValueDBFullSupport,
};
// data[table][id] => any (can be Buffer, or number)
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 Readable.from(Object.keys(this.data[table] || {}).slice(0, limit));
}
streamValues(table, limit) {
return Readable.from(Object.values(this.data[table] || {}).slice(0, limit));
}
streamEntries(table, limit) {
return 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];
});
}
}