Build the new-comment notification email
Node · Node · beginner · greenfield
Adds the notification email builder. A single escapeHtml helper covers the five HTML-special characters and is applied to every interpolation; the article URL is built from the server-generated slug with encodeURIComponent. No template engine, just correctly escaped template literals.
Emails render in recipients' mail clients with HTML enabled; a script or markup injection here lands in every subscriber's inbox.
Requirements
- Implement `buildCommentEmail({ articleTitle, articleId, authorName, commentBody })` returning the HTML body for the "new comment on your article" notification.
- All four fields are strings from the database; `authorName` and `commentBody` are user-entered and must be treated as hostile, `articleTitle` is author-entered and equally untrusted, `articleId` is a URL-safe slug generated by the server.
- Every interpolated value must be HTML-escaped so user input can never inject markup or scripts into the email.
- The article link points at `https://blog.example.com/articles/{articleId}` with the id URL-encoded.
- The email shows the author's name in bold, the article title as the link text, and the comment body in a blockquote.
Files touched
- src/notifications/commentEmail.js
--- src/notifications/commentEmail.js
+const ESCAPE_MAP = {
+ '&': '&',
+ '<': '<',
+ '>': '>',
+ '"': '"',
+ "'": ''',
+};
+
+function escapeHtml(value) {
+ return value.replace(/[&<>"']/g, (ch) => ESCAPE_MAP[ch]);
+}
+
+export function buildCommentEmail({ articleTitle, articleId, authorName, commentBody }) {
+ const articleUrl = `https://blog.example.com/articles/${encodeURIComponent(articleId)}`;
+ return [
+ `<p><strong>${escapeHtml(authorName)}</strong> commented on ` +
+ `<a href="${articleUrl}">${escapeHtml(articleTitle)}</a>:</p>`,
+ `<blockquote>${escapeHtml(commentBody)}</blockquote>`,
+ ].join('\n');
+}
+