salix/print/lib/router.js

66 lines
1.9 KiB
JavaScript
Raw Normal View History

2019-01-22 08:55:35 +00:00
const reportEngine = require('./reportEngine.js');
const emailEngine = require('./emailEngine');
const express = require('express');
const routes = require(`../config/routes.json`);
module.exports = app => {
2019-01-25 14:08:11 +00:00
this.path = `${appPath}/report`;
2019-01-22 08:55:35 +00:00
/**
* 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) => {
reportEngine.toPdf(name, request).then(stream => {
2019-01-25 14:08:11 +00:00
response.setHeader('Content-Disposition', `attachment; filename="${name}.pdf"`);
response.setHeader('Content-type', 'application/pdf');
2019-01-22 08:55:35 +00:00
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));
});
};