UNPKG

stream-flow-control

Version:
85 lines (77 loc) 2.58 kB
const {FlowFirst} = require('../../lib'); const {Readable, Transform, Writable} = require('stream'); describe('FlowFirst test', () => { test('Flows the first message that arrives', done => { const start = Readable.from(['{"id": 1}', '{"id": 2}', '{"id": 3}']); let results = {}; const transform1 = new Transform({ objectMode: true, transform(chunk, encoding, callback) { const obj = JSON.parse(chunk); obj.from = 1; if(obj.id !== 1) { setTimeout(()=> { this.push(obj); callback(); }, 150); } else { this.push(obj); callback(); } } }); const transform2 = new Transform({ objectMode: true, transform(chunk, encoding, callback) { const obj = JSON.parse(chunk); obj.from = 2; if(obj.id !== 2) { setTimeout(()=> { this.push(obj); callback(); }, 120); } else { this.push(obj); callback(); } } }); const transform3 = new Transform({ objectMode: true, transform(chunk, encoding, callback) { const obj = JSON.parse(chunk); obj.from = 3; if(obj.id !== 3) { setTimeout(()=> { this.push(obj); callback(); }, 100); } else { this.push(obj); callback(); } } }); const checkFinish = () => { expect(results).toEqual({m1: 1, m2: 2, m3: 3}); done(); }; const writeStream = new Writable({ objectMode: true, write(chunk, encoding, callback) { results[`m${chunk.id}`] = chunk.from; callback(); } }); writeStream.on('finish', checkFinish); const flow = new FlowFirst({ identify(payload) { return payload.id; } }); flow.pipe(writeStream); start.pipe(transform1).pipe(flow); start.pipe(transform2).pipe(flow); start.pipe(transform3).pipe(flow); }); });