1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-01 13:47:06 +01:00
metamask-extension/app/scripts/lib/stream-provider.js

60 lines
1.5 KiB
JavaScript
Raw Normal View History

2015-12-19 07:05:16 +01:00
const Duplex = require('readable-stream').Duplex
const inherits = require('util').inherits
module.exports = StreamProvider
inherits(StreamProvider, Duplex)
function StreamProvider(){
Duplex.call(this, {
objectMode: true,
})
2015-12-21 01:22:18 +01:00
this._payloads = {}
2015-12-19 07:05:16 +01:00
}
// public
StreamProvider.prototype.send = function(payload){
2016-01-17 08:38:40 +01:00
throw new Error('StreamProvider - does not support synchronous RPC calls. called: "'+payload.method+'"')
2015-12-19 07:05:16 +01:00
}
StreamProvider.prototype.sendAsync = function(payload, callback){
2015-12-21 01:22:18 +01:00
// console.log('StreamProvider - sending payload', payload)
this._payloads[payload.id] = [payload, callback]
// console.log('payload for plugin:', payload)
2015-12-19 07:05:16 +01:00
this.push(payload)
}
// private
2015-12-21 01:22:18 +01:00
StreamProvider.prototype._onResponse = function(response){
// console.log('StreamProvider - got response', payload)
var data = this._payloads[response.id]
if (!data) throw new Error('StreamProvider - Unknown response id')
delete this._payloads[response.id]
var payload = data[0]
var callback = data[1]
// logging
var res = Array.isArray(response) ? response : [response]
;(Array.isArray(payload) ? payload : [payload]).forEach(function(payload, index){
console.log('plugin response:', payload.id, payload.method, payload.params, '->', res[index].result)
})
callback(null, response)
2015-12-19 07:05:16 +01:00
}
// stream plumbing
StreamProvider.prototype._read = noop
StreamProvider.prototype._write = function(msg, encoding, cb){
this._onResponse(msg)
cb()
}
// util
function noop(){}