Skip to content

Commit

Permalink
feat: add progress events (#540)
Browse files Browse the repository at this point in the history
  • Loading branch information
AVaksman committed Mar 9, 2020
1 parent b9a3ac8 commit 1834059
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {GoogleAuth, GoogleAuthOptions} from 'google-auth-library';
import {CredentialBody} from 'google-auth-library';
import * as r from 'teeny-request';
import * as retryRequest from 'retry-request';
import {Duplex, DuplexOptions, PassThrough, Readable, Writable} from 'stream';
import {Duplex, DuplexOptions, Readable, Transform, Writable} from 'stream';
import {teenyRequest} from 'teeny-request';

import {Interceptor} from './service-object';
Expand Down Expand Up @@ -453,7 +453,8 @@ export class Util {
) {
onComplete = onComplete || util.noop;

const writeStream = new PassThrough();
const writeStream = new ProgressStream();
writeStream.on('progress', evt => dup.emit('progress', evt));
dup.setWritable(writeStream);

const defaultReqOpts = {
Expand Down Expand Up @@ -864,5 +865,20 @@ export class Util {
}
}

/**
* Basic Passthrough Stream that records the number of bytes read
* every time the cursor is moved.
*/
class ProgressStream extends Transform {
bytesRead = 0;
// tslint:disable-next-line: no-any
_transform(chunk: any, encoding: string, callback: Function) {
this.bytesRead += chunk.length;
this.emit('progress', {bytesWritten: this.bytesRead, contentLength: '*'});
this.push(chunk);
callback();
}
}

const util = new Util();
export {util};
15 changes: 15 additions & 0 deletions test/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,21 @@ describe('common/util', () => {
util.makeWritableStream(dup, {makeAuthenticatedRequest() {}});
});

it('dup should emit a progress event with the bytes written', done => {
let happened = false;

const dup = duplexify();
dup.on('progress', (progress: {}) => {
happened = true;
});

util.makeWritableStream(dup, {makeAuthenticatedRequest() {}}, util.noop);
dup.write(Buffer.from('abcdefghijklmnopqrstuvwxyz'), 'utf-8', util.noop);

assert.strictEqual(happened, true);
done();
});

it('should emit an error if the request fails', done => {
const dup = duplexify();
const fakeStream = new stream.Writable();
Expand Down

0 comments on commit 1834059

Please sign in to comment.