Clean up "download()" implementation

Reduce nesting, remove repetition.
This commit is contained in:
Miroslav Bajtoš 2016-11-10 14:20:38 +01:00
parent fc3475bf1f
commit 9997041093
1 changed files with 47 additions and 47 deletions

View File

@ -233,16 +233,44 @@ exports.download = function(provider, req, res, container, file, cb) {
var range = null;
if (req) {
if (!req) {
// TODO(rfeng/bajtos) We should let the caller now about the problem!
return;
}
if (req.headers) {
range = req.headers.range || '';
}
if (range) {
if (!range) {
return download(params);
}
provider.getFile(params.container, params.remote, function(err, stats) {
if (err) {
return handleError(res, err);
}
setupPartialDownload(params, stats, res);
download(params);
});
function download(params) {
var reader = provider.download(params);
res.type(fileName);
reader.pipe(res);
reader.on('error', function onReaderError(err) {
handleError(res, err);
} else {
});
reader.on('end', function onReaderEnd() {
cb();
});
}
};
function setupPartialDownload(params, stats, res) {
var total = stats.size;
var parts = range.replace(/bytes=/, '').split('-');
@ -258,32 +286,4 @@ exports.download = function(provider, req, res, container, file, cb) {
res.set('Content-Range', 'bytes ' + params.start + '-' + params.end + '/' + total);
res.set('Accept-Ranges', 'bytes');
res.set('Content-Length', chunksize);
var reader = provider.download(params);
res.type(fileName);
reader.pipe(res);
reader.on('error', function(err) {
handleError(res, err);
});
reader.on('end', function() {
cb();
});
}
});
} else {
var reader = provider.download(params);
res.type(fileName);
reader.pipe(res);
reader.on('error', function(err) {
handleError(res, err);
});
reader.on('end', function() {
cb();
});
}
}
};