OverviewFilesCommitsIssuesDocsReleasesPeers

hyper-booking / node_modules / bare-fetch / lib / response-stream.js

60 lines · javascript ref:
const { Readable } = require('bare-stream')
const { Gunzip, Deflate } = require('bare-zlib')

module.exports = class ResponseStream extends Readable {
  constructor(response) {
    super()

    this._response = response
    this._response.socket.unref()

    const encoding = response.headers['content-encoding']

    switch (encoding) {
      case 'gzip':
        this._decoder = new Gunzip()
        break
      case 'deflate':
        this._decoder = new Deflate()
        break
      default:
        this._decoder = null
    }
  }

  _open(cb) {
    if (this._response.socket) this._response.socket.ref()

    const stream = this._decoder ? this._response.pipe(this._decoder) : this._response

    stream
      .on('data', this._ondata.bind(this))
      .on('end', this._onend.bind(this))
      .on('error', this._onerror.bind(this))

    cb(null)
  }

  _read() {
    this._response.resume()
  }

  _predestroy() {
    this._response.destroy()
  }

  _ondata(data) {
    if (this.push(data) === false) {
      this._response.pause()
    }
  }

  _onend() {
    this.push(null)
  }

  _onerror(err) {
    this.destroy(err)
  }
}