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

49 lines
1.2 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
const mx = through.obj(function (chunk, enc, cb) {
const name = chunk.name
const data = chunk.data
if (!name) {
console.warn(`ObjectMultiplex - Malformed chunk without name "${chunk}"`)
return cb()
}
const substream = mx.streams[name]
2016-04-15 06:22:04 +02:00
if (!substream) {
console.warn(`ObjectMultiplex - 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) {
const 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
}