Skip to content

Commit b71d827

Browse files
authored
feat(File): support file callback (#442)
1 parent ed977f2 commit b71d827

File tree

2 files changed

+27
-11
lines changed

2 files changed

+27
-11
lines changed

src/file.js

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ const s3 = require('./uploader/s3');
55
const AVError = require('./error');
66
const AVRequest = require('./request').request;
77
const Promise = require('./promise');
8+
const { tap } = require('./utils');
9+
const debug = require('debug')('leancloud:file');
810

911
module.exports = function(AV) {
1012

@@ -426,12 +428,7 @@ module.exports = function(AV) {
426428
metaData: this.attributes.metaData,
427429
};
428430
this._qiniu_key = key;
429-
return AVRequest(route, null, null, 'POST', data).then(response => {
430-
if (response.mime_type) {
431-
this.set('mime_type', response.mime_type);
432-
}
433-
return response;
434-
});
431+
return AVRequest(route, null, null, 'POST', data);
435432
},
436433

437434
/**
@@ -453,6 +450,11 @@ module.exports = function(AV) {
453450
this._previousSave = this._source.then(({ data, type }) =>
454451
this._fileToken(type)
455452
.then(uploadInfo => {
453+
if (uploadInfo.mime_type) {
454+
this.set('mime_type', uploadInfo.mime_type);
455+
}
456+
this._token = uploadInfo.token;
457+
456458
let uploadPromise;
457459
switch (uploadInfo.provider) {
458460
case 's3':
@@ -466,11 +468,13 @@ module.exports = function(AV) {
466468
uploadPromise = qiniu(uploadInfo, data, this, options);
467469
break;
468470
}
469-
return uploadPromise.catch(err => {
470-
// destroy this file object when upload fails.
471-
this.destroy();
472-
throw err;
473-
});
471+
return uploadPromise.then(
472+
tap(() => this._callback(true)),
473+
(error) => {
474+
this._callback(false);
475+
throw error;
476+
}
477+
);
474478
})
475479
);
476480
} else if (this.attributes.url && this.attributes.metaData.__source === 'external') {
@@ -495,6 +499,15 @@ module.exports = function(AV) {
495499
}
496500
return this._previousSave;
497501
},
502+
503+
_callback(success) {
504+
AVRequest('fileCallback', null, null, 'post', {
505+
token: this._token,
506+
result: success,
507+
}).catch(debug);
508+
delete this._token;
509+
},
510+
498511
/**
499512
* fetch the file from server. If the server's representation of the
500513
* model differs from its current attributes, they will be overriden,

src/utils/index.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,11 @@ const getSessionToken = (authOptions) => {
2424
}
2525
};
2626

27+
const tap = interceptor => value => ((interceptor(value), value));
28+
2729
module.exports = {
2830
isNullOrUndefined,
2931
ensureArray,
3032
getSessionToken,
33+
tap,
3134
};

0 commit comments

Comments
 (0)