UNPKG

@naturalcycles/db-lib

Version:

Lowest Common Denominator API to supported Databases

53 lines (52 loc) 1.69 kB
import { Pipeline } from '@naturalcycles/nodejs-lib/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] ||= {}; for (const id of ids) { 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] ||= {}; for (const [id, v] of entries) { this.data[table][id] = v; } } streamIds(table, limit) { return Pipeline.fromArray(Object.keys(this.data[table] || {}).slice(0, limit)); } streamValues(table, limit) { return Pipeline.fromArray(Object.values(this.data[table] || {}).slice(0, limit)); } streamEntries(table, limit) { return Pipeline.fromArray(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]; }); } }