aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/lib/stream-provider.js
blob: 3e7f443c8f50112d06eaca147765c2e3dd1b3cff (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const Duplex = require('readable-stream').Duplex
const inherits = require('util').inherits

module.exports = StreamProvider


inherits(StreamProvider, Duplex)

function StreamProvider(){
  Duplex.call(this, {
    objectMode: true,
  })

  this._handlers = {}
}

// public

StreamProvider.prototype.send = function(payload){
  throw new Error('StreamProvider - does not support synchronous RPC calls')
}

StreamProvider.prototype.sendAsync = function(payload, callback){
//   console.log('StreamProvider - sending payload', payload)
  this._handlers[payload.id] = callback
  this.push(payload)
}

// private

StreamProvider.prototype._onResponse = function(payload){
//   console.log('StreamProvider - got response', payload)
  var callback = this._handlers[payload.id]
  if (!callback) throw new Error('StreamProvider - Unknown response id')
  delete this._handlers[payload.id]
  callback(null, payload)
}

// stream plumbing

StreamProvider.prototype._read = noop

StreamProvider.prototype._write = function(msg, encoding, cb){
  this._onResponse(msg)
  cb()
}

// util

function noop(){}