UNPKG

@x5e/gink

Version:

an eventually consistent database

76 lines 2.76 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Accumulator = void 0; const Database_1 = require("./Database"); const Container_1 = require("./Container"); const utils_1 = require("./utils"); const builders_1 = require("./builders"); class Accumulator extends Container_1.Container { constructor(database, address) { super(database, address, builders_1.Behavior.ACCUMULATOR); if (this.address.timestamp < 0) { (0, utils_1.ensure)(address.offset === builders_1.Behavior.ACCUMULATOR); } } static get(database, muid) { if (!muid) { muid = { timestamp: -1, medallion: -1, offset: builders_1.Behavior.ACCUMULATOR, }; } database = database || Database_1.Database.recent; return new Accumulator(database, muid); } static async create(database, meta) { database = database || Database_1.Database.recent; const muid = await Container_1.Container.addContainer({ behavior: builders_1.Behavior.ACCUMULATOR, database, meta, }); return new Accumulator(database, muid); } async addNumber(increment, meta) { const value = BigInt(Math.floor(increment * 1000000000)); return this.addEntry(undefined, value, meta); } async getNumber(asOf) { const billionths = await this.database.store.getBillionths(this.address, asOf); return Number(billionths) / 1000000000; } async getBillionths(asOf) { return this.database.store.getBillionths(this.address, asOf); } async addBillionths(value, meta) { return this.addEntry(undefined, value, meta); } async size(_asOf) { throw new Error("size not defined for accumulators"); } async clear(purge, meta) { throw new Error("accumulators cannot be cleared"); } async reset(toTime, _recurse, meta) { let current = await this.getBillionths(); let pastValue = 0n; if (toTime) { pastValue = await this.getBillionths(toTime); } await this.addBillionths(-1n * current + pastValue, meta); } /** * Generates a JSON representation of the data in the box (the box itself is transparent). * Mostly intended for demo/debug purposes. * @param indent true to pretty print * @param asOf effective time * @param seen (internal use only! Prevent cycles from breaking things) * @returns a JSON string */ async toJson(_indent = false, asOf, _seen) { return String(await this.getNumber(asOf)); } } exports.Accumulator = Accumulator; //# sourceMappingURL=Accumulator.js.map