@energyweb/node-red-contrib-green-proof-worker
Version:
## Peer dependencies
89 lines (88 loc) • 3.65 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.LedgerSqlite = void 0;
const tslib_1 = require("tslib");
const z = tslib_1.__importStar(require("zod"));
const errors_1 = require("../errors");
const node_1 = require("../node");
const types_1 = require("../types");
const InputMessage = z.union([
z.object({
topic: z.literal('get_ledger_entries'),
payload: z.object({
ledgerQuery: z.array(z.object({
accountId: z.string().uuid(),
rootUnitId: z.string().uuid(),
})),
}).passthrough()
}),
z.object({
topic: z.literal('update_ledger'),
payload: z.object({
ledgerUpdate: z.array(types_1.LedgerEntry),
}).passthrough()
})
]);
const Config = z.object({
sqliteConfig: z.string(),
});
const LedgerSqlite = (api) => class LedgerSqlite extends node_1.Node {
constructor(config) {
super(api, config, InputMessage);
const parsedConfig = Config.parse(config);
const configNode = this.api.getNode(parsedConfig.sqliteConfig);
if (!configNode) {
throw new errors_1.GGPError(errors_1.ErrorCode.SqliteConfigNotFound, {});
}
this.database = configNode.database;
}
async onInput(message) {
const db = await this.database;
switch (message.topic) {
case 'get_ledger_entries':
const ledgerQuery = message.payload.ledgerQuery;
if (ledgerQuery.length === 0) {
return this.sendBuilder(message)
.addPayload({ ledger: [] })
.sendToOutput(0);
}
this.api.status({ fill: 'green', shape: 'dot', text: 'Reading ledger...' });
const result = await db
.selectFrom('ledger')
.selectAll()
.where(({ eb, refTuple, tuple }) => eb(refTuple('account_id', 'root_unit_id'), 'in', ledgerQuery.flatMap((accountWithUnit) => tuple(accountWithUnit.accountId, accountWithUnit.rootUnitId))))
.execute()
.finally(() => this.api.status({}));
return this.sendBuilder(message)
.addPayload({
ledger: result.map(r => ({
accountId: r.account_id,
rootUnitId: r.root_unit_id,
volume: r.volume
}))
})
.sendToOutput(0);
case 'update_ledger':
this.api.status({ fill: 'green', shape: 'dot', text: 'Updating ledger...' });
if (message.payload.ledgerUpdate.length === 0) {
return this.sendBuilder(message).sendToOutput(0);
}
await db
.insertInto('ledger')
.values(message.payload.ledgerUpdate.map(e => ({
account_id: e.accountId,
root_unit_id: e.rootUnitId,
volume: e.volume
})))
.onConflict(c => c.columns(['account_id', 'root_unit_id']).doUpdateSet((eb) => ({
volume: eb.ref('excluded.volume'),
})))
.execute()
.finally(() => this.api.status({}));
return this.sendBuilder(message).sendToOutput(0);
default:
throw new errors_1.GGPError(errors_1.ErrorCode.LedgerUnknownTopic, { topic: message.topic });
}
}
};
exports.LedgerSqlite = LedgerSqlite;