UNPKG

sqmicro-connection

Version:

Connection abstraction for SQ Micro.

63 lines (51 loc) 1.47 kB
const { Transform, Writable } = require('stream'); const toJSON = require('./to-json'); const events = 'close data drain end error finish readable pipe unpipe'.split(' '); const MAX_LEN = 128; class S extends Transform { get name() { return this._A; } constructor(name) { super({ objectMode: true }); this._A = name || 'S'; bindEvents(this, events, this.name); } _transform(chunk, encoding, done) { console.log(`${this.name}: ${JSON.stringify(chunk)}`); this.push(chunk); done(); } } class W extends Writable { get name() { return this._A; } constructor(name) { super({ objectMode: true }); this._A = name || 'W'; bindEvents(this, events, this.name); } _write(chunk, encoding, done) { console.log(`${this.name}: ${JSON.stringify(chunk)}`); done(); } } const a = new S('a'); const b = new S('b'); const w = new S('w'); a.pipe(b).pipe(w); a.write({an: 'object', n: 1}); a.write({an: 'object', n: 2}); a.write({an: 'object', n: 3}); a.end(); function bindEvents(target, events, name) { events.forEach(e => { target.on(e, a => console.log(`${name}: ♮ ${e}(${stringify(a)})`)); }); } function stringify(o) { if (o === undefined) return; if (o.name) return o.name; let s = toJSON(o, 0); if (s.length > MAX_LEN) { s = s.substr(0, MAX_LEN - 1) + '…'; } return s; }