compile(template);
Utils.Logger.info(`Rendering ${template.name} as ${type}…`);
let content = '';
try {
const html = render(template.name, data);
content = type === 'html' ? html : Utils.toText(html, settings.plainTextOpts);
Utils.Logger.info('Rendering successful!');
} catch (ex) {
const msg = `Could not preview email: ${ex.message}`;
Utils.Logger.error(msg);
content = msg;
}
res.writeHead(200, {
'Content-Type': CONTENT_TYPES[type]
});
return res.end(content, 'utf8');
};
};
const sendAction = (req, res, params, template) => {
const to = params.query.to || settings.testEmail;
Utils.Logger.info(`Sending ${template.name}…`);
if (to) {
let data = null;
try {
data = template.route.data && template.route.data.call(res, params);
} catch (ex) {
Utils.Logger.error(`Exception in ${template.name} data function: ${ex.message}`);
return;
}
const result = Mailer.send({
to,
data,
template: template.name,
subject: '[TEST] ' + template.name
});
let msg = '';
if (result === false) {
res.writeHead(500);
msg = 'Did not send test email, something went wrong. Check the logs.';
} else {
res.writeHead(200);
const reallySentEmail = !!process.env.MAIL_URL;
msg = reallySentEmail ? `Sent test email to ${to}` : `Sent email to STDOUT`;
}
res.end(msg);
} else {
res.writeHead(400);
res.end('No testEmail provided.');
}
};
const types = {
preview: previewAction('html'),
text: previewAction('text'),
send: sendAction
};
_.each(types, (action, type) => {
const path = `/${settings.routePrefix}/${type}` + template.route.path;
const name = Utils.capitalizeFirstChar(template.name);
const routeName = '' + type + name;
Utils.Logger.info(`Add route: [${routeName}] at path ${path}`);
Picker.route(path, (params, req, res) => action(req, res, params, template));
});
};