UNPKG

@openhps/core

Version:

Open Hybrid Positioning System - Core component

80 lines 2.49 kB
import { PushError } from './events'; import { EventEmitter } from 'events'; import { PushPromise } from './PushPromise'; /** * Edge provides the connection between two nodes * Nodes have access to inlet and outlet interfaces that only * allow functionality needed for the type of port. * * As a part of the graph that can not be modified, this object * has the ability to perform error handling. * @category Graph */ export class Edge extends EventEmitter { constructor(inputNode, outputNode) { super(); this.inputNode = inputNode; this.outputNode = outputNode; // Register default push and pull handling this.on('push', this._onPush.bind(this)); this.on('pull', this._onPull.bind(this)); } _onPush(data, options) { return this.outputNode.push(data, options); } _onPull(options) { return this.inputNode.pull(options); } /** * Push data to the output node * @param {DataFrame | DataFrame[]} data Data frame to push * @param {PushOptions} [options] Push options * @returns {Promise<void>} Push promise */ push(data, options = {}) { return new PushPromise((resolve, reject, complete) => { const newOptions = Object.assign(Object.assign({}, options), { lastNode: this.inputNode.uid }); const pushListeners = this.listeners('push'); Promise.all(pushListeners.map(listener => listener(data, newOptions))).then(() => { resolve(); }).catch(ex => { // Error handling is done in the edge if (Array.isArray(data)) { data.forEach(frame => { this.inputNode.emit('error', new PushError(frame.uid, this.outputNode.uid, ex)); }); } else { this.inputNode.emit('error', new PushError(data.uid, this.outputNode.uid, ex)); } }); }); } /** * Pull data from the input node * @param {PullOptions} [options] Pull options * @returns {Promise<void>} Pull promise */ pull(options) { return new Promise((resolve, reject) => { const pullListeners = this.listeners('pull'); Promise.all(pullListeners.map(listener => listener(options))).then(() => { resolve(); }).catch(reject); }); } emit(name, event) { return this.inputNode.emit(name, event); } on(name, listener) { this.removeAllListeners(name); return super.on(name, listener); } get inletNode() { return this.inputNode; } get outletNode() { return this.outputNode; } }