Skip to content

Commit

Permalink
Combined export logic with index to limit duplicate code. Removed exp…
Browse files Browse the repository at this point in the history
…ortToCsv function
  • Loading branch information
brandonpassley committed Jun 29, 2016
1 parent 976900b commit 3fe57e7
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 50 deletions.
42 changes: 21 additions & 21 deletions dist/admin/admin.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ exports.create = create;
exports.update = update;
exports.destroy = destroy;
exports.destroyMultiple = destroyMultiple;
exports.exportToCsv = exportToCsv;
exports.importFromCsv = importFromCsv;

var _lodash = require('lodash');
Expand Down Expand Up @@ -53,21 +52,27 @@ function getSchema(req, res, next) {
}

/**
* Gets a list of documents
* Gets a list of documents based on a search query
* If no search query is sent, it will return all documents
* If export=true is found in the request query, we will output CSV instead of JSON
*/
function index(req, res, next) {
var limit = Number(req.query.limit) || 20;
var skip = Number(req.query.skip) || 0;
var sort = req.query.sort || '-createdAt';

// If export is sent as true in our query, we'll output a CSV instead of JSON
var shouldExport = !!req.query.export;

var searchFilters = req.query.filters || [];
var searchQuery = {};

// See if we have a populate method for our class
// if we don't populatedFields should be blank
var populatedFields = '';

if (typeof req.class.populateForAdmin === 'function') {
// Don't populate the fields if we are exporting
if (typeof req.class.populateForAdmin === 'function' && !shouldExport) {
populatedFields = req.class.populateForAdmin();
}

Expand Down Expand Up @@ -140,7 +145,19 @@ function index(req, res, next) {
return req.class.find(searchQuery).count().then(function (count) {

return req.class.find(searchQuery).populate(populatedFields).sort(sort).limit(limit).skip(skip).then(function (result) {
return { itemCount: count, items: result };

if (shouldExport) {
var currentDate = (0, _moment2.default)().format('YYYY-MM-D');
var filename = req.class.modelName + '-export-' + currentDate + '-.csv';
var headers = Object.keys(req.class.schema.paths);
var convertedString = (0, _adminHelper.convertToCsv)(result, headers);
res.set('Content-Type', 'text/csv');
res.set('Content-Disposition', 'attachment; filename=' + filename);
res.send(convertedString);
return null;
} else {
return { itemCount: count, items: result };
}
});
});
}).then(utils.respondWithResult(res, blacklistResponseAttributes)).catch(utils.handleError(next));
Expand Down Expand Up @@ -208,23 +225,6 @@ function destroyMultiple(req, res, next) {
}).catch(utils.handleError(next));
}

/**
* Gets a list of documents and converts them to a CSV string
*/
function exportToCsv(req, res, next) {
var searchFilters = req.query.filters;
var searchQuery = !!searchFilters ? utils.buildQuery(searchFilters) : {};
var currentDate = (0, _moment2.default)().format('YYYY-MM-D');
var filename = req.class.modelName + '-export-' + currentDate + '-.csv';
req.class.find(searchQuery).then(function (result) {
var headers = Object.keys(req.class.schema.paths);
var convertedString = (0, _adminHelper.convertToCsv)(result, headers);
res.set('Content-Type', 'text/csv');
res.set('Content-Disposition', 'attachment; filename=' + filename);
res.send(convertedString);
}).catch(utils.handleError(next));
}

/**
* Imports objects from a csv file hosted at req.body.url
*/
Expand Down
1 change: 0 additions & 1 deletion dist/admin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ function setUser(_user) {
*/
router.get('/:className/schema', auth.hasRole('admin'), attachClass(), controller.getSchema);
router.post('/:className/deleteMultiple', auth.hasRole('admin'), attachClass(), controller.destroyMultiple);
router.get('/:className/exportToCsv', auth.hasRole('admin'), attachClass(), controller.exportToCsv);
router.post('/:className/importFromCsv', auth.hasRole('admin'), attachClass(), controller.importFromCsv);

router.get('/:className/', auth.hasRole('admin'), attachClass(), controller.index);
Expand Down
52 changes: 26 additions & 26 deletions src/admin/admin.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,21 +36,27 @@ export function getSchema(req, res, next) {
}

/**
* Gets a list of documents
* Gets a list of documents based on a search query
* If no search query is sent, it will return all documents
* If export=true is found in the request query, we will output CSV instead of JSON
*/
export function index(req, res, next) {
let limit = Number(req.query.limit) || 20;
let skip = Number(req.query.skip) || 0;
let sort = req.query.sort || '-createdAt';

// If export is sent as true in our query, we'll output a CSV instead of JSON
let shouldExport = !!req.query.export;

let searchFilters = req.query.filters || [];
let searchQuery = {};

// See if we have a populate method for our class
// if we don't populatedFields should be blank
let populatedFields = ''
let populatedFields = '';

if (typeof req.class.populateForAdmin === 'function') {
// Don't populate the fields if we are exporting
if (typeof req.class.populateForAdmin === 'function' && !shouldExport) {
populatedFields = req.class.populateForAdmin();
}

Expand Down Expand Up @@ -88,7 +94,7 @@ export function index(req, res, next) {
} else {
relationshipQuery[searchField]['$eq'] = searchFilters[i].value;
}

relationshipPromises.push(relationshipClass.find(relationshipQuery, '_id'));

} else {
Expand All @@ -105,7 +111,7 @@ export function index(req, res, next) {

// Loop through the results to collect the IDs for each relationship
for (let i = results.length - 1; i >= 0; i--) {
let resultIds = results[i].map((o) => { return o._id.toString() });
let resultIds = results[i].map((o) => { return o._id.toString(); });
let tmpQuery = {};
tmpQuery[queryOptions[i][0]] = { $in: resultIds };
searchQuery['$and'].push(tmpQuery);
Expand All @@ -129,7 +135,20 @@ export function index(req, res, next) {
.limit(limit)
.skip(skip)
.then((result) => {
return { itemCount: count, items: result };

if (shouldExport) {
let currentDate = moment().format('YYYY-MM-D');
let filename = `${req.class.modelName}-export-${currentDate}-.csv`;
let headers = Object.keys(req.class.schema.paths);
let convertedString = convertToCsv(result, headers);
res.set('Content-Type', 'text/csv');
res.set('Content-Disposition', 'attachment; filename=' + filename);
res.send(convertedString);
return null;

} else {
return { itemCount: count, items: result };
}
});
});
})
Expand All @@ -143,7 +162,7 @@ export function index(req, res, next) {
export function show(req, res, next) {
// See if we have a populate method for our class
// if we don't populatedFields should be blank
let populatedFields = ''
let populatedFields = '';

if (typeof req.class.populateForAdmin === 'function') {
populatedFields = req.class.populateForAdmin();
Expand Down Expand Up @@ -218,25 +237,6 @@ export function destroyMultiple(req, res, next) {
.catch(utils.handleError(next));
}

/**
* Gets a list of documents and converts them to a CSV string
*/
export function exportToCsv(req, res, next) {
let searchFilters = req.query.filters;
let searchQuery = !!searchFilters ? utils.buildQuery(searchFilters) : {};
let currentDate = moment().format('YYYY-MM-D');
let filename = `${req.class.modelName}-export-${currentDate}-.csv`;
req.class.find(searchQuery)
.then((result) => {
let headers = Object.keys(req.class.schema.paths);
let convertedString = convertToCsv(result, headers);
res.set('Content-Type', 'text/csv');
res.set('Content-Disposition', 'attachment; filename=' + filename);
res.send(convertedString);
})
.catch(utils.handleError(next));
}

/**
* Imports objects from a csv file hosted at req.body.url
*/
Expand Down
2 changes: 0 additions & 2 deletions src/admin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@ export function setUser(_user) {
router.get('/:className/schema', auth.hasRole('admin'), attachClass(), controller.getSchema);
router.post('/:className/deleteMultiple', auth.hasRole('admin'),
attachClass(), controller.destroyMultiple);
router.get('/:className/exportToCsv', auth.hasRole('admin'),
attachClass(), controller.exportToCsv);
router.post('/:className/importFromCsv', auth.hasRole('admin'),
attachClass(), controller.importFromCsv);

Expand Down

0 comments on commit 3fe57e7

Please sign in to comment.