Skip to content
Snippets Groups Projects
Commit 8de89944 authored by Vytor Calixto's avatar Vytor Calixto :space_invader:
Browse files

Add function in response middleware 2 flat objects

parent 7ba4aac4
No related branches found
No related tags found
No related merge requests found
Pipeline #
......@@ -3,13 +3,51 @@ const log = require(`${libs}/log`)(module);
const xml = require('js2xmlparser');
const csv = require('csv-express');
// Custom generic middleware used respond requests.
// The function reads the req.query.format param and respond in json, xml or csv
// Função para transformar um resultado que contém objetos com arrays aninhados em vários objetos
// sem arrays aninhandos
function flatObj(obj) {
let flatList = [];
let tempObj = {};
Object.keys(obj).forEach((key) => {
if(obj[key] instanceof Array) {
obj[key].forEach((i) => {
let flatten = flatObj(i);
if(flatten instanceof Array) {
flatten.forEach((j) => {
flatList.push(Object.assign({}, tempObj, j));
});
} else {
flatList.push(Object.assign({}, tempObj, flatten));
}
});
} else if(obj[key] instanceof Object) {
tempObj = Object.assign({}, tempObj, obj[key]);
} else {
tempObj[key] = obj[key];
}
});
if(flatList.length > 0) return flatList;
return tempObj;
}
// Custom generic middleware used to answer requests.
// The function reads the req.query.format param and answers in json, xml or csv
function response(value) {
return (req, res, next) => {
if (req.query.format === 'csv') {
let result = [];
req.result.forEach((i) => {
let flatten = flatObj(i);
if(flatten instanceof Array) {
result = [...result, ...flatten];
} else {
result.push(flatten);
}
});
res.attachment(`${value}.csv`);
res.csv(req.result, true);
res.csv(result, true);
} else if (req.query.format === 'xml') {
res.send(xml.parse('result', { [value]: req.result }));
} else {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment