salix/print/core/router.js

87 lines
2.5 KiB
JavaScript

const Report = require('./report');
const Email = require('./email');
module.exports = app => {
app.get(`/api/report/:name`, async(req, res, next) => {
const args = Object.assign({}, req.body, req.query);
try {
const report = new Report(req.params.name, args);
const stream = await report.toPdfStream();
res.setHeader('Content-type', 'application/pdf');
stream.pipe(res);
} catch (e) {
next(e);
}
});
app.get(`/api/email/:name`, async(req, res, next) => {
const args = req.query;
const requiredArgs = ['recipient', 'clientId'];
const hasRequiredArgs = requiredArgs.every(arg => {
return args[arg];
});
if (!hasRequiredArgs)
res.json({message: 'Required params recipient, clientId'});
try {
const email = new Email(req.params.name, args);
if (args.isPreview === 'true') {
const rendered = await email.render();
res.send(rendered);
} else {
await email.send();
res.status(200).json({message: 'Sent'});
}
} catch (e) {
next(e);
}
});
/**
* 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}`, async(request, response) => {
const args = Object.assign({}, request.body, request.query);
const report = new Report(name, args);
const stream = await report.toPdf();
response.setHeader('Content-type', 'application/pdf');
stream.pipe(response);
});
}
/**
* 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);
});
});
}
};