UNPKG

@ocap/statedb-memory

Version:

OCAP statedb adapter that uses memory as backend statedb, just for test purpose

94 lines (92 loc) 3.01 kB
import { name } from "../package.mjs"; import { StateDBTable } from "@ocap/statedb"; import Debug from "debug"; import omit from "lodash/omit.js"; //#region src/table/base.ts const debug = Debug(name); /** * 内存表基类 * 使用 LokiJS Collection 作为底层存储 */ var MemoryTable = class MemoryTable extends StateDBTable { constructor({ name: name$1, uniqIndex, balanceTable, syncBalance = false, db }) { super(uniqIndex); this.name = name$1; this.balanceTable = balanceTable; this.syncBalance = syncBalance; if (this.syncBalance && !this.balanceTable) throw new Error("balanceTable is required when syncBalance is true"); if (!db) throw new Error("db is required for MemoryTable"); this.collection = db.addCollection(name$1, { unique: [this.primaryKey], clone: true }); this.markReady(); } async _create(key, attrs = {}, context) { const id = this.generatePrimaryKey(key); if (await MemoryTable.prototype._get.call(this, id)) throw new Error(`${this.name} already exists: ${key}`); debug(`insert ${this.name}`, attrs); const insertAttrs = { ...attrs }; if (this.syncBalance) delete insertAttrs.tokens; const result = await this.collection.insert({ [this.primaryKey]: id, ...insertAttrs }); if (this.syncBalance && attrs.tokens) { debug(`update balance for ${this.name}`, attrs); result.tokens = await this.balanceTable.updateBalance({ address: attrs.address, tokens: attrs.tokens, context: attrs.context }, context); } return result; } async _get(key, _context) { if (!key) return null; const id = this.generatePrimaryKey(key); const result = await this.collection.by(this.primaryKey, id) ?? null; if (result && this.syncBalance) { const balance = await this.balanceTable.getBalance(result.address); result.tokens = { ...result.tokens || {}, ...balance }; } return result; } _history(_key, _context) { return []; } async _update(key, updates, context) { const id = this.generatePrimaryKey(key); const doc = await MemoryTable.prototype._get.call(this, id); if (!doc) throw new Error(`${this.name} does not exists: ${key}`); Object.assign(doc, updates); const updateAttrs = { ...doc }; if (this.syncBalance) delete updateAttrs.tokens; await this.collection.update(updateAttrs); if (this.syncBalance && doc.tokens) { debug(`update balance for ${this.name}`, doc); doc.tokens = await this.balanceTable.updateBalance({ address: doc.address, tokens: doc.tokens, context: doc.context }, context); } return doc; } updateOrCreate(exist, state, ctx) { const id = this.generatePrimaryKey(state); const attrs = omit(state, this.uniqIndex ?? []); if (!id) throw new Error("Cannot update or create without uniq index"); if (exist) return this.update(id, attrs, ctx); return this.create(id, attrs, ctx); } _reset(_context) { this.collection.removeWhere({}); } }; var base_default = MemoryTable; //#endregion export { base_default as default };