UNPKG

transgate

Version:

Agent-based task flow framework

80 lines (79 loc) 2.31 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Process an item read from Input Gate and write into Output Gate */ class Agent { /** * @param {InGate} ingate - Input gate * @param {OutGate} outgate - Output gate or its map */ constructor(ingate, outgate) { this.ingate = ingate; this.outgate = outgate; } /** * Processes should be defined before all transactions */ async before() { } /** * Processes should be defined after all transactions */ async after() { } async run() { await this.before(); try { let item; while ((item = await this.ingate.receive()) !== null) { const result = await this.main(item, this.outgate); if (result !== undefined) { await this.sendToOutgate(result); } } //console.info('send null') await this.sendToOutgate(null); } finally { await this.after(); } } /** * Process main Promise function * @param {object} item - read item * @param {OutputGate} outgate - Output gate * @return {object|array} written item(s). it is an array if output is plural. `undefined` is not written. */ async main(item, outgate) { } async sendToOutgate(item) { if (this.outgate.send) { await this.outgate.send(item); } else { await Promise.all(Object.values(this.outgate).map(it => it.send(item))); } } /** * Shorthand to create Agent * @param {Gate} ingate - Input gate * @param {Gate|Object<string, Gate>} outgate - Output gate or its map * @param {Promise} main - Process main Promise function * @return {Agent} created one */ static create(ingate, outgate, main) { const action = new Agent(ingate, outgate); action.main = main; return action; } /** * Start all agents * @param {Agent} ...agents - Agent(s) * @return {Promise} A Promise that resolves when all agents have done */ static async all(...agents) { await Promise.all(agents.map(t => t.run())); } } exports.Agent = Agent;