1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-24 02:58:09 +01:00
metamask-extension/app/scripts/lib/obj-multiplex.js

45 lines
1.0 KiB
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 {
if (substream.push) substream.push(data)
2016-04-15 06:22:04 +02:00
}
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
}
// ignore streams (dont display orphaned data warning)
mx.ignoreStream = function (name) {
mx.streams[name] = true
}
2016-04-15 06:22:04 +02:00
return mx
}