65 lines
1.8 KiB
JavaScript
65 lines
1.8 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}/report`;
|
|
|
|
/**
|
|
* Enables a report
|
|
*
|
|
* @param {String} name - Report state path
|
|
*/
|
|
function registerReport(name) {
|
|
if (!name) throw new Error('Report name required');
|
|
|
|
app.get(`/api/report/${name}`, (request, response, next) => {
|
|
reportEngine.toPdf(name, request).then(stream => {
|
|
response.setHeader('Content-type', 'application/pdf');
|
|
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(`/api/email/${name}`, (request, response, next) => {
|
|
emailEngine.render(name, request).then(rendered => {
|
|
response.send(rendered.html);
|
|
}).catch(e => {
|
|
next(e);
|
|
});
|
|
});
|
|
|
|
app.post(`/api/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(`/api/assets`, express.static(staticPath));
|
|
});
|
|
};
|