Skip to content
Snippets Groups Projects

Csv download

Open ns17 requested to merge SMPPIR/Loopback-API-Example:CSV_download into master
2 files
+ 166
0
Compare changes
  • Side-by-side
  • Inline
Files
2
+ 61
0
@@ -21,4 +21,65 @@ along with SMPPIR-CheckIn. If not, see <https://www.gnu.org/licenses/>.
'use strict';
module.exports = function(Category) {
Category.csvexport = function(type, res, callback ) {
var datetime = new Date();
var datetimeFuture = new Date(datetime.getFullYear(), datetime.getMonth(), datetime.getDate()+7)
res.set('Expires', datetimeFuture+'');
res.set('Cache-Control', 'max-age=0, no-cache, must-revalidate, proxy-revalidate');
res.set('Last-Modified', datetime+'');
res.set('Content-Type','application/force-download');
res.set('Content-Type','application/octet-stream');
res.set('Content-Type','application/download');
res.set('Content-Disposition','attachment;filename=category.csv');
res.set('Content-Transfer-Encoding','binary');
Category.find(function(err, categories) {
// conversão JSON para CSV
var itemsFormatted = [];
// cabeçalho do csv
var headers = {
category_name: "category_name",
category_description: "category_description",
id: "id"
};
categories.forEach((item) => {
itemsFormatted.push({
category_name: item.category_name,
category_description: item.category_description,
id: item.id
});
});
if (headers) {
itemsFormatted.unshift(headers);
}
var jsonObject = JSON.stringify(itemsFormatted);
var array = typeof jsonObject != 'object' ? JSON.parse(jsonObject) : jsonObject;
var csv = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ';' // aqui muda o separador do csv
line += array[i][index];
}
csv += line + '\r\n';
}
res.send(csv);
});
};
Category.remoteMethod('csvexport',
{
accepts: [
{arg: 'type', type: 'string', required: false},
{arg: 'res', type: 'object', 'http': {source: 'res'}}
],
returns: {},
// Para usar o 'type' -> http: {path: '/csv/:type', verb: 'get'}
http: {path: '/csv', verb: 'get'},
});
};
Loading