Vulcan/packages/vulcan-email/lib/server/routes.js

68 lines
2.4 KiB
JavaScript
Raw Normal View History

import { Picker } from 'meteor/meteorhacks:picker';
import { runQuery, Strings, getSetting } from 'meteor/vulcan:lib';
import VulcanEmail from '../namespace.js';
2016-06-23 16:42:06 +09:00
Meteor.startup(function () {
2017-03-24 10:35:19 +09:00
_.forEach(VulcanEmail.emails, (email, key) => {
2016-04-13 12:34:41 +09:00
// template live preview routes
2017-08-19 16:13:59 +09:00
Picker.route(email.path, async (params, req, res) => {
2016-04-13 12:34:41 +09:00
let html;
// if email has a custom way of generating test HTML, use it
if (typeof email.getTestHTML !== "undefined") {
2016-04-13 12:34:41 +09:00
html = email.getTestHTML.bind(email)(params);
2016-04-13 12:34:41 +09:00
} else {
2016-04-13 12:34:41 +09:00
2018-05-10 18:34:59 +09:00
const locale = params.query.locale || getSetting('locale');
// else get test object (sample post, comment, user, etc.)
const testVariables = (typeof email.testVariables === 'function' ? email.testVariables() : email.testVariables) || {};
// delete params.query so we don't pass it to GraphQL query
delete params.query;
// merge test variables with params from URL
// TODO: this is currently hardcoded to work with the SingleXYZInput type, maybe bad idea?
const variables = { input: { selector: { ...testVariables, ...params } } };
2018-05-10 18:34:59 +09:00
const result = email.query ? await runQuery(email.query, variables, { locale }) : {data: {}};
// if email has a data() function, merge it with results of query
const emailTestData = email.data ? {...result.data, ...email.data(variables)} : result.data;
2017-08-19 16:13:59 +09:00
const subject = typeof email.subject === 'function' ? email.subject(emailTestData) : email.subject;
2016-04-13 12:34:41 +09:00
emailTestData.__ = Strings[locale];
const template = VulcanEmail.getTemplate(email.template);
const htmlContent = template(emailTestData)
// then apply email template to properties, and wrap it with buildTemplate
html = VulcanEmail.buildTemplate(htmlContent, emailTestData);
2016-04-13 12:34:41 +09:00
// remove Strings object to avoid echoing it out
delete emailTestData.__;
html += `
2017-08-19 16:13:59 +09:00
<h4 style="margin: 20px;"><code>Subject: ${subject}</code></h4>
<div style="border: 1px solid #999; padding: 10px 20px; margin: 20px;">
<pre><code>${JSON.stringify(emailTestData, null, 2)}</code></pre>
</div>
`
}
// return html
res.end(html);
});
// raw template
Picker.route("/email/template/:template", (params, req, res) => {
2017-03-24 10:35:19 +09:00
res.end(VulcanEmail.templates[params.template]);
});
});
});