salix/print/lib/router.js

67 lines
1.9 KiB
JavaScript

const reportEngine = require('./reportEngine.js');
const emailEngine = require('./emailEngine');
const express = require('express');
const routes = require(`../config/routes.json`);
module.exports = app => {
this.path = `${appPath}/reports`;
/**
* Enables a report
*
* @param {String} name - Report state path
*/
function registerReport(name) {
if (!name) throw new Error('Report name required');
app.get(`/report/${name}`, (request, response, next) => {
response.setHeader('Content-Disposition', `attachment; filename="${name}.pdf"`);
response.setHeader('Content-type', 'application/pdf');
reportEngine.toPdf(name, request).then(stream => {
stream.pipe(response);
}).catch(e => {
next(e);
});
});
}
/**
* Enables a email
*
* @param {String} name - Report state path
*/
function registerEmail(name) {
if (!name) throw new Error('Email name required');
app.get(`/email/${name}`, (request, response, next) => {
emailEngine.render(name, request).then(rendered => {
response.send(rendered.html);
}).catch(e => {
next(e);
});
});
app.post(`/email/${name}`, (request, response, next) => {
emailEngine.toEmail(name, request).then(() => {
response.status(200).json({status: 200});
}).catch(e => {
next(e);
});
});
}
/**
* Register routes
*/
routes.forEach(route => {
if (route.type === 'email')
registerEmail(route.name);
else if (route.type === 'report')
registerReport(route.name);
const staticPath = this.path + `/${route.name}/assets`;
app.use(`/assets`, express.static(staticPath));
});
};