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

72 lines
1.7 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)
2016-01-31 08:14:58 +01:00
var id = payload.id
if (Array.isArray(payload)) {
id = 'batch'+payload[0].id
}
this._payloads[id] = [payload, callback]
2015-12-21 01:22:18 +01:00
// console.log('payload for plugin:', payload)
2015-12-19 07:05:16 +01:00
this.push(payload)
}
StreamProvider.prototype.isConnected = function(){
return true
}
2015-12-19 07:05:16 +01:00
// private
2015-12-21 01:22:18 +01:00
StreamProvider.prototype._onResponse = function(response){
// console.log('StreamProvider - got response', payload)
2016-01-31 08:14:58 +01:00
var id = response.id
if (Array.isArray(response)) {
id = 'batch'+response[0].id
}
var data = this._payloads[id]
2015-12-21 01:22:18 +01:00
if (!data) throw new Error('StreamProvider - Unknown response id')
2016-01-31 08:14:58 +01:00
delete this._payloads[id]
2015-12-21 01:22:18 +01:00
var payload = data[0]
var callback = data[1]
// logging
var res = Array.isArray(response) ? response : [response]
2016-01-31 08:16:47 +01:00
// ;(Array.isArray(payload) ? payload : [payload]).forEach(function(payload, index){
// console.log('plugin response:', payload.id, payload.method, payload.params, '->', res[index].result)
// })
2015-12-21 01:22:18 +01:00
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(){}