salix/print/core/router.js

87 lines
2.5 KiB
JavaScript
Raw Normal View History

2019-10-29 06:46:44 +00:00
const Report = require('./report');
const Email = require('./email');
2019-01-22 08:55:35 +00:00
module.exports = app => {
2019-10-31 11:43:04 +00:00
app.get(`/api/report/:name`, async(req, res, next) => {
2019-10-24 05:41:54 +00:00
const args = Object.assign({}, req.body, req.query);
2019-10-31 11:43:04 +00:00
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);
}
2019-10-24 05:41:54 +00:00
});
2019-10-31 11:43:04 +00:00
app.get(`/api/email/:name`, async(req, res, next) => {
2019-10-29 06:46:44 +00:00
const args = req.query;
2019-10-31 11:43:04 +00:00
const requiredArgs = ['recipient', 'clientId'];
2019-10-29 06:46:44 +00:00
const hasRequiredArgs = requiredArgs.every(arg => {
return args[arg];
2019-10-24 05:41:54 +00:00
});
2019-10-29 06:46:44 +00:00
if (!hasRequiredArgs)
2019-10-31 11:43:04 +00:00
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);
2019-10-29 06:46:44 +00:00
}
2019-10-24 05:41:54 +00:00
});
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');
2019-10-24 05:41:54 +00:00
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);
2019-01-22 08:55:35 +00:00
});
}
/**
* Enables a email
*
* @param {String} name - Report state path
*/
function registerEmail(name) {
if (!name) throw new Error('Email name required');
2019-01-28 11:28:22 +00:00
app.get(`/api/email/${name}`, (request, response, next) => {
2019-01-22 08:55:35 +00:00
emailEngine.render(name, request).then(rendered => {
response.send(rendered.html);
}).catch(e => {
next(e);
});
});
2019-01-28 11:28:22 +00:00
app.post(`/api/email/${name}`, (request, response, next) => {
2019-01-22 08:55:35 +00:00
emailEngine.toEmail(name, request).then(() => {
response.status(200).json({status: 200});
}).catch(e => {
next(e);
});
});
}
};