Skip to content

Commit

Permalink
fix: restart on missing range
Browse files Browse the repository at this point in the history
  • Loading branch information
kukhariev committed Jul 16, 2019
1 parent b84b430 commit c0b2744
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
18 changes: 17 additions & 1 deletion src/uploadx/src/uploaderx.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { UploaderX } from './uploaderx';
import { UploaderX, getRangeEnd } from './uploaderx';
import { UploadxOptions } from './interfaces';
import { Uploader } from './uploader';

Expand All @@ -24,6 +24,22 @@ describe('Uploader', () => {
});
});

describe('getRangeEnd', () => {
it('invalid ranges', () => {
expect(getRangeEnd(undefined)).toEqual(-1);
expect(getRangeEnd('')).toEqual(-1);
expect(getRangeEnd('invalid')).toEqual(-1);
expect(getRangeEnd('Range: bytes=-1')).toEqual(-1);
expect(getRangeEnd('Range: bytes=-5')).toEqual(-1);
expect(getRangeEnd('Range: bytes=0--5')).toEqual(-1);
});
it('valid ', () => {
expect(getRangeEnd('Range: bytes=0-1')).toEqual(1);
expect(getRangeEnd('Range: bytes=0-0')).toEqual(0);
expect(getRangeEnd('Range: bytes=0--1')).toEqual(-1);
});
});

function getFile(): File {
return new File([''], 'filename.mp4');
}
20 changes: 14 additions & 6 deletions src/uploadx/src/uploaderx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ export class UploaderX extends Uploader {
headers
});
const location = this.statusType === 200 && this.getValueFromResponse('location');
if (!location) {
throw new Error('Invalid or missing Location header');
}
this.offset = this.responseStatus === 201 ? 0 : undefined;
return resolveUrl(location, this.endpoint);
}
Expand Down Expand Up @@ -56,16 +59,16 @@ export class UploaderX extends Uploader {
return this.getOffsetFromResponse();
}

protected getOffsetFromResponse() {
if (this.statusType === 300) {
protected getOffsetFromResponse(): number {
if (this.responseStatus === 308) {
const range = this.getValueFromResponse('Range');
const end = range.split(/0-/).pop();
return end && +end + 1;
} else if (this.statusType === 200) {
return getRangeEnd(range) + 1;
}
if (this.statusType === 200) {
return this.size;
}
return;
}

protected onCancel(): void {
this.request({ method: 'DELETE' });
}
Expand All @@ -74,3 +77,8 @@ export class UploaderX extends Uploader {
this.headers.Authorization = `Bearer ${token}`;
}
}

export function getRangeEnd(range = ''): number {
const end = +range.split(/0-/)[1];
return end >= 0 ? end : -1;
}

0 comments on commit c0b2744

Please sign in to comment.