1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-30 16:18:07 +01:00
metamask-extension/app/scripts/lib/obj-multiplex.js

41 lines
905 B
JavaScript
Raw Normal View History

2016-04-15 06:22:04 +02:00
const through = require('through2')
module.exports = ObjectMultiplex
2016-06-21 22:18:32 +02:00
function ObjectMultiplex (opts) {
2016-04-15 06:22:04 +02:00
opts = opts || {}
// create multiplexer
2016-06-21 22:18:32 +02:00
var mx = through.obj(function (chunk, enc, cb) {
2016-04-15 06:22:04 +02:00
var name = chunk.name
var data = chunk.data
var substream = mx.streams[name]
if (!substream) {
console.warn('orphaned data for stream ' + name)
2016-04-15 06:22:04 +02:00
} else {
substream.push(data)
}
return cb()
})
mx.streams = {}
// create substreams
2016-06-21 22:18:32 +02:00
mx.createStream = function (name) {
var substream = mx.streams[name] = through.obj(function (chunk, enc, cb) {
2016-04-15 06:22:04 +02:00
mx.push({
name: name,
data: chunk,
})
return cb()
})
2016-06-21 22:18:32 +02:00
mx.on('end', function () {
2016-04-15 06:22:04 +02:00
return substream.emit('end')
})
if (opts.error) {
2016-06-21 22:18:32 +02:00
mx.on('error', function () {
2016-04-15 06:22:04 +02:00
return substream.emit('error')
})
}
return substream
}
return mx
}