Skip to content

Commit

Permalink
(api) add download parameter to csv download
Browse files Browse the repository at this point in the history
  • Loading branch information
ubergesundheit committed Feb 5, 2018
1 parent 4c66570 commit 1727dbf
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 4 deletions.
11 changes: 8 additions & 3 deletions packages/api/lib/controllers/measurementsController.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const
{ BadRequestError, UnsupportedMediaTypeError } = require('restify-errors'),
{ Measurement, Box } = require('@sensebox/opensensemap-api-models'),
csvstringify = require('csv-stringify'),
{ checkContentType } = require('../helpers/apiUtils'),
{ checkContentType, createDownloadFilename } = require('../helpers/apiUtils'),
{
retrieveParameters,
validateFromToTimeParams
Expand Down Expand Up @@ -88,9 +88,10 @@ const getData = function getData (req, res, next) {
* @apiUse BBoxParam
* @apiUse ExposureFilterParam
* @apiParam {String=createdAt,value,lat,lon,height,boxId,boxName,exposure,sensorId,phenomenon,unit,sensorType} [columns=createdAt,value,lat,lon] Comma separated list of columns to export.
* @apiParam {Boolean=true,false} [download=true] Set the `content-disposition` header to force browsers to download instead of displaying.
*/
const getDataMulti = function getDataMulti (req, res, next) {
const { boxId, bbox, exposure, delimiter, columns, fromDate, toDate, phenomenon } = req._userParams;
const { boxId, bbox, exposure, delimiter, columns, fromDate, toDate, phenomenon, download } = req._userParams;

// build query
const queryParams = {
Expand Down Expand Up @@ -123,6 +124,9 @@ const getDataMulti = function getDataMulti (req, res, next) {
.then(function (cursor) {

res.header('Content-Type', 'text/csv');
if (download === 'true') {
res.header('Content-Disposition', `attachment; filename=${createDownloadFilename(req.date(), 'download', [phenomenon, ...columns], 'csv')}`);
}
const stringifier = csvstringify({ columns, delimiter, header: 1 });

cursor
Expand Down Expand Up @@ -308,7 +312,8 @@ module.exports = {
{ predef: 'columnsGetDataMulti' },
{ predef: 'bbox' },
{ predef: 'toDate' },
{ predef: 'fromDate' }
{ predef: 'fromDate' },
{ name: 'download', defaultValue: 'true', allowedValues: ['true', 'false'] },
]),
validateFromToTimeParams,
getDataMulti
Expand Down
9 changes: 8 additions & 1 deletion packages/api/lib/helpers/apiUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,12 @@ const getVersion = (function () {
}
})();

const createDownloadFilename = function createDownloadFilename (date, action, params, format) {
return `opensensemap_org-${action}-${encodeURI(encodeURI(params.join('-')))}-${date.toISOString()
.replace(/-|:|\.\d*Z/g, '')
.replace('T', '_')}.${format}`;
};

module.exports = {
addCache,
clearCache,
Expand All @@ -157,5 +163,6 @@ module.exports = {
Honeybadger,
postToSlack,
getVersion,
redactEmail
redactEmail,
createDownloadFilename
};
32 changes: 32 additions & 0 deletions tests/tests/007-download-data-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,38 @@ describe('downloading data', function () {
});
});

it('should have the content-disposition header when calling /boxes/data/', function () {
return chakram.get(`${BASE_URL}/boxes/data/?boxid=${boxIds[0]},${boxIds[1]}&phenomenon=Temperatur`)
.then(function (response) {
expect(response).to.have.status(200);
expect(response.body).not.to.be.empty;
expect(response).to.have.header('content-type', 'text/csv');
expect(response).to.have.header('content-disposition', /opensensemap_org-download-Temperatur-createdAt-value-lat-lon-/);
/* eslint-disable no-unused-vars */
const [_, ...lines] = response.body.split('\n');
/* eslint-enable no-unused-vars */
expect(lines).to.have.lengthOf(9);

return chakram.wait();
});
});

it('should not have the content-disposition header when calling /boxes/data/?download=false', function () {
return chakram.get(`${BASE_URL}/boxes/data/?boxid=${boxIds[0]},${boxIds[1]}&phenomenon=Temperatur&download=false`)
.then(function (response) {
expect(response).to.have.status(200);
expect(response.body).not.to.be.empty;
expect(response).to.have.header('content-type', 'text/csv');
expect(response).to.not.have.header('content-disposition', /opensensemap_org-download-Temperatur-createdAt-value-lat-lon-/);
/* eslint-disable no-unused-vars */
const [_, ...lines] = response.body.split('\n');
/* eslint-enable no-unused-vars */
expect(lines).to.have.lengthOf(9);

return chakram.wait();
});
});

it('should return the data for /boxes/:boxId/data/:sensorId in descending order', function () {
return chakram.get(`${BASE_URL}/boxes/${boxIds[0]}/data/${boxes[0].sensors[1]._id}?from-date=2016-01-01T00:00:00Z&to-date=2016-01-31T23:59:59Z`)
.then(function (response) {
Expand Down

0 comments on commit 1727dbf

Please sign in to comment.