Skip to content

Commit

Permalink
feat: allow returning response headers alongside date via didUpload.w…
Browse files Browse the repository at this point in the history
…ithHeaders (#1)
  • Loading branch information
guillaumedeslandes authored Sep 29, 2020
1 parent 9866537 commit 9785339
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 5 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,13 @@ uploader.on('didUpload', e => {
});
```

```js
uploader.on('didUpload.withHeaders', e => {
// Handle finished upload
// Use `e.data`, `e.headers`, `e.status` and `e.xhr` as needed
});
```

#### Failed Uploading

```js
Expand Down
26 changes: 22 additions & 4 deletions addon/uploaders/uploader.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,14 +108,32 @@ export default EmberObject.extend(Evented, {
},

/**
* Triggers didUpload event with given params and sets isUploading to false
* Triggers didUpload and didUpload.withHeaders events with given params
* and sets isUploading to false
*
* @param {object} data Object of data supplied to the didUpload event
* @param {object} status Status of the request
* @param {object} xhr XMLHttpRequest instance for this request
* @return {object} Returns the given data
*/
didUpload (data) {
didUpload (data, status, xhr) {
set(this, 'isUploading', false);
this.trigger('didUpload', data);

const headers = {};
xhr
.getAllResponseHeaders().trim().split(/[\r\n]+/)
.forEach((header) => {
const [key, value] = header.split(': ');
headers[key] = value;
}),
this.trigger('didUpload.withHeaders',
{
data,
headers,
status,
xhr
});
return data;
},

Expand Down Expand Up @@ -210,8 +228,8 @@ export default EmberObject.extend(Evented, {
*/
ajaxPromise (settings) {
return new Promise((resolve, reject) => {
settings.success = (data) => {
run(null, resolve, this.didUpload(data));
settings.success = (data, status, xhr) => {
run(null, resolve, this.didUpload(data, status, xhr));
};

settings.error = (jqXHR, responseText, errorThrown) => {
Expand Down
6 changes: 5 additions & 1 deletion tests/unit/uploader-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ module('EmberUploader.Uploader', function(hooks) {
});

test("uploads to the given url", function(assert) {
assert.expect(1);
assert.expect(2);

let uploader = Uploader.extend({
url: '/upload',
Expand All @@ -96,6 +96,10 @@ module('EmberUploader.Uploader', function(hooks) {
assert.ok(true);
});

uploader.on('didUpload.withHeaders', function(data) {
assert.ok(true);
});

uploader.upload(file);
});

Expand Down

0 comments on commit 9785339

Please sign in to comment.