2019-11-18 14:04:51 +00:00
|
|
|
const Report = require('../core/report');
|
|
|
|
|
|
|
|
module.exports = app => {
|
|
|
|
app.get(`/api/report/:name`, async(req, res, next) => {
|
|
|
|
const args = req.query;
|
|
|
|
const requiredArgs = ['clientId'];
|
2019-11-19 09:32:09 +00:00
|
|
|
const argList = requiredArgs.join(',');
|
2019-11-18 14:04:51 +00:00
|
|
|
const hasRequiredArgs = requiredArgs.every(arg => {
|
|
|
|
return args[arg];
|
|
|
|
});
|
|
|
|
|
|
|
|
try {
|
2019-11-19 09:32:09 +00:00
|
|
|
if (!hasRequiredArgs)
|
|
|
|
throw new Error(`Required properties not found [${argList}]`);
|
|
|
|
|
2020-03-16 08:51:29 +00:00
|
|
|
const reportName = req.params.name;
|
|
|
|
const fileName = getFileName(reportName, args);
|
|
|
|
const report = new Report(reportName, args);
|
2019-11-18 14:04:51 +00:00
|
|
|
const stream = await report.toPdfStream();
|
2020-03-16 08:51:29 +00:00
|
|
|
|
2019-11-18 14:04:51 +00:00
|
|
|
res.setHeader('Content-type', 'application/pdf');
|
2020-03-16 08:51:29 +00:00
|
|
|
res.setHeader('Content-Disposition', `inline; filename="${fileName}"`);
|
|
|
|
|
2019-11-18 14:04:51 +00:00
|
|
|
stream.pipe(res);
|
2019-11-19 09:32:09 +00:00
|
|
|
} catch (error) {
|
|
|
|
next(error);
|
2019-11-18 14:04:51 +00:00
|
|
|
}
|
|
|
|
});
|
2020-03-16 08:51:29 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns all the params that ends with id
|
|
|
|
* @param {object} args - Params object
|
|
|
|
*
|
|
|
|
* @return {array} List of identifiers
|
|
|
|
*/
|
|
|
|
function getIdentifiers(args) {
|
|
|
|
const identifiers = [];
|
|
|
|
const keys = Object.keys(args);
|
|
|
|
|
|
|
|
for (let arg of keys) {
|
|
|
|
// FIXME: #2197 - Remove clientId as a required param
|
|
|
|
if (arg != 'clientId' && arg.endsWith('Id'))
|
|
|
|
identifiers.push(arg);
|
|
|
|
}
|
|
|
|
|
|
|
|
return identifiers;
|
|
|
|
}
|
|
|
|
|
|
|
|
function getFileName(name, args) {
|
|
|
|
const identifiers = getIdentifiers(args);
|
|
|
|
const params = [];
|
|
|
|
params.push(name);
|
|
|
|
|
|
|
|
for (let id of identifiers)
|
|
|
|
params.push(args[id]);
|
|
|
|
|
|
|
|
const fileName = params.join('_');
|
|
|
|
|
|
|
|
return `${fileName}.pdf`;
|
|
|
|
}
|
2019-11-18 14:04:51 +00:00
|
|
|
};
|