Skip to content

Commit

Permalink
fix(email-plugin): Fix Handlebars "cannot resolve property" error
Browse files Browse the repository at this point in the history
Closes #259
  • Loading branch information
michaelbromley committed Feb 11, 2020
1 parent 66bc98c commit 2984a90
Show file tree
Hide file tree
Showing 6 changed files with 156 additions and 65 deletions.
2 changes: 1 addition & 1 deletion packages/email-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"dateformat": "^3.0.3",
"express": "^4.16.4",
"fs-extra": "^8.0.1",
"handlebars": "^4.1.2",
"handlebars": "^4.7.3",
"mjml": "^4.3.0",
"nodemailer": "^5.0.0"
},
Expand Down
21 changes: 16 additions & 5 deletions packages/email-plugin/src/handlebars-mjml-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,14 @@ export class HandlebarsMjmlGenerator implements EmailGenerator {
const compiledFrom = Handlebars.compile(from);
const compiledSubject = Handlebars.compile(subject);
const compiledTemplate = Handlebars.compile(template);
const fromResult = compiledFrom(templateVars);
const subjectResult = compiledSubject(templateVars);
const mjml = compiledTemplate(templateVars);
// We enable prototype properties here, aware of the security implications
// described here: https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access
// This is needed because some Vendure entities use getters on the entity
// prototype (e.g. Order.total) which may need to be interpolated.
const templateOptions: RuntimeOptions = { allowProtoPropertiesByDefault: true };
const fromResult = compiledFrom(templateVars, { allowProtoPropertiesByDefault: true });
const subjectResult = compiledSubject(templateVars, { allowProtoPropertiesByDefault: true });
const mjml = compiledTemplate(templateVars, { allowProtoPropertiesByDefault: true });
const body = mjml2html(mjml).html;
return { from: fromResult, subject: subjectResult, body };
}
Expand All @@ -37,14 +42,20 @@ export class HandlebarsMjmlGenerator implements EmailGenerator {
}

private registerHelpers() {
Handlebars.registerHelper('formatDate', (date: Date, format: string | object) => {
Handlebars.registerHelper('formatDate', (date: Date | undefined, format: string | object) => {
if (!date) {
return date;
}
if (typeof format !== 'string') {
format = 'default';
}
return dateFormat(date, format);
});

Handlebars.registerHelper('formatMoney', (amount: number) => {
Handlebars.registerHelper('formatMoney', (amount?: number) => {
if (amount == null) {
return amount;
}
return (amount / 100).toFixed(2);
});
}
Expand Down
Loading

0 comments on commit 2984a90

Please sign in to comment.