From 99970410933700062743a172b7616310db5e21bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20Bajto=C5=A1?= Date: Thu, 10 Nov 2016 14:20:38 +0100 Subject: [PATCH] Clean up "download()" implementation Reduce nesting, remove repetition. --- lib/storage-handler.js | 94 +++++++++++++++++++++--------------------- 1 file changed, 47 insertions(+), 47 deletions(-) diff --git a/lib/storage-handler.js b/lib/storage-handler.js index 4063bf6..96080ea 100644 --- a/lib/storage-handler.js +++ b/lib/storage-handler.js @@ -233,57 +233,57 @@ exports.download = function(provider, req, res, container, file, cb) { var range = null; - if (req) { - if (req.headers) { - range = req.headers.range || ''; + if (!req) { + // TODO(rfeng/bajtos) We should let the caller now about the problem! + return; + } + + if (req.headers) { + range = req.headers.range || ''; + } + + if (!range) { + return download(params); + } + + provider.getFile(params.container, params.remote, function(err, stats) { + if (err) { + return handleError(res, err); } - if (range) { - provider.getFile(params.container, params.remote, function(err, stats) { - if (err) { - handleError(res, err); - } else { - var total = stats.size; + setupPartialDownload(params, stats, res); + download(params); + }); - var parts = range.replace(/bytes=/, '').split('-'); - var partialstart = parts[0]; - var partialend = parts[1]; + function download(params) { + var reader = provider.download(params); - params.start = parseInt(partialstart, 10); - params.end = partialend ? parseInt(partialend, 10) : total - 1; + res.type(fileName); - var chunksize = (params.end - params.start) + 1; - - res.status(206); - 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(); - }); - } + reader.pipe(res); + reader.on('error', function onReaderError(err) { + handleError(res, err); + }); + reader.on('end', function onReaderEnd() { + cb(); + }); } }; + +function setupPartialDownload(params, stats, res) { + var total = stats.size; + + var parts = range.replace(/bytes=/, '').split('-'); + var partialstart = parts[0]; + var partialend = parts[1]; + + params.start = parseInt(partialstart, 10); + params.end = partialend ? parseInt(partialend, 10) : total - 1; + + var chunksize = (params.end - params.start) + 1; + + res.status(206); + res.set('Content-Range', 'bytes ' + params.start + '-' + params.end + '/' + total); + res.set('Accept-Ranges', 'bytes'); + res.set('Content-Length', chunksize); +};