51 lines
1.3 KiB
JavaScript
51 lines
1.3 KiB
JavaScript
const Report = require('../core/report');
|
|
|
|
module.exports = app => {
|
|
app.get(`/api/report/:name`, async(req, res, next) => {
|
|
try {
|
|
const reportName = req.params.name;
|
|
const fileName = getFileName(reportName, req.args);
|
|
const report = new Report(reportName, req.args);
|
|
const stream = await report.toPdfStream();
|
|
|
|
res.setHeader('Content-type', 'application/pdf');
|
|
res.setHeader('Content-Disposition', `inline; filename="${fileName}"`);
|
|
|
|
stream.pipe(res);
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
});
|
|
|
|
/**
|
|
* 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) {
|
|
if (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`;
|
|
}
|
|
};
|