all files / merkle-trie/ readStream.js

100% Statements 25/25
100% Branches 6/6
100% Functions 3/3
100% Lines 25/25
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     14× 14× 14× 14× 14× 14× 14×       77× 14× 14×         14× 14× 14×   12× 13× 13× 13× 49×   13× 13× 13× 12×                
const Readable = require('readable-stream').Readable
 
module.exports = class TrieReadable extends Readable {
  constructor (opts = {}, link, store) {
    opts.objectMode = true
    super(opts)
    this._link = link
    this._opts = opts
    this._store = store
    this._reading = false
    this._numOfReading = 0
  }
 
  _read () {
    if (!this._reading) {
      this._reading = true
      this.__read()
    }
  }
 
  __read () {
    this._store.get(this._link).then(vertex => {
      this.push(vertex)
      if (vertex.isLeaf) {
        this.push(null)
      } else {
        for (let [, edge] of vertex.edges) {
          this._numOfReading++
          const readStream = new TrieReadable(this._opts, edge, this._store)
          readStream.on('data', vertex => {
            this.push(vertex)
          })
          readStream.on('end', vertex => {
            this._numOfReading--
            if (this._numOfReading === 0) {
              this.push(null)
            }
          })
        }
      }
    })
  }
}