|  | 
|  | 1 | +'use strict' | 
|  | 2 | + | 
|  | 3 | +const Transform = require('readable-stream').Transform | 
|  | 4 | + | 
|  | 5 | +/* | 
|  | 6 | +  A transform stream to track progress events on file upload | 
|  | 7 | +
 | 
|  | 8 | +  When the progress flag is passed to the HTTP api, the stream | 
|  | 9 | +  emits progress events like such: | 
|  | 10 | +
 | 
|  | 11 | +  { | 
|  | 12 | +    Name  string | 
|  | 13 | +    Hash  string `json:",omitempty"` | 
|  | 14 | +    Bytes int64  `json:",omitempty"` | 
|  | 15 | +    Size  string `json:",omitempty"` | 
|  | 16 | +  } | 
|  | 17 | +
 | 
|  | 18 | +  This class will take care of detecting such | 
|  | 19 | +  events and calling the associated track method | 
|  | 20 | +  with the bytes sent so far as parameter. It will | 
|  | 21 | +  also skip them from the stream, emitting only | 
|  | 22 | +  when the final object has been uploaded and we | 
|  | 23 | +  got a hash. | 
|  | 24 | +*/ | 
|  | 25 | +class ProgressStream extends Transform { | 
|  | 26 | +  constructor (opts) { | 
|  | 27 | +    opts = Object.assign(opts || {}, { objectMode: true }) | 
|  | 28 | +    super(opts) | 
|  | 29 | +    this._track = opts.track || (() => {}) | 
|  | 30 | +  } | 
|  | 31 | + | 
|  | 32 | +  static fromStream (track, stream) { | 
|  | 33 | +    const prog = new ProgressStream({ track }) | 
|  | 34 | +    return stream.pipe(prog) | 
|  | 35 | +  } | 
|  | 36 | + | 
|  | 37 | +  _transform (chunk, encoding, callback) { | 
|  | 38 | +    if (chunk && | 
|  | 39 | +      typeof chunk.Bytes !== 'undefined' && | 
|  | 40 | +      typeof chunk.Hash === 'undefined') { | 
|  | 41 | +      this._track(chunk.Bytes) | 
|  | 42 | +      return callback() | 
|  | 43 | +    } | 
|  | 44 | + | 
|  | 45 | +    callback(null, chunk) | 
|  | 46 | +  } | 
|  | 47 | +} | 
|  | 48 | + | 
|  | 49 | +module.exports = ProgressStream | 
0 commit comments