Transactional mail: minor template-sender refactoring

This commit is contained in:
Alexey Zinkevych 2019-04-02 16:35:57 +03:00
parent e588e218b6
commit 8b39a101cd
3 changed files with 24 additions and 16 deletions

View file

@ -1,4 +1,4 @@
{ {
"extends": "nodemailer", "extends": "nodemailer",
"parserOptions": { "ecmaVersion": 2017 } "parserOptions": { "ecmaVersion": 2018 }
} }

View file

@ -5,21 +5,26 @@ const tools = require('./tools');
const templates = require('../models/templates'); const templates = require('../models/templates');
class TemplateSender { class TemplateSender {
constructor({ templateId, maxMails = 100 } = {}) { constructor(options) {
if (!templateId) { this.defaultOptions = {
throw new Error('Cannot create template sender without templateId'); maxMails: 100,
} ...options
};
this.templateId = templateId;
this.maxMails = maxMails;
} }
async send(options) { async send(params) {
const options = { ...this.defaultOptions, ...params };
this._validateMailOptions(options); this._validateMailOptions(options);
const [mailer, template] = await Promise.all([ const [mailer, template] = await Promise.all([
mailers.getOrCreateMailer(options.sendConfigurationId), mailers.getOrCreateMailer(
templates.getById(options.context, this.templateId, false) options.sendConfigurationId
),
templates.getById(
options.context,
options.templateId,
false
)
]); ]);
const html = tools.formatTemplate( const html = tools.formatTemplate(
@ -46,8 +51,11 @@ class TemplateSender {
} }
_validateMailOptions(options) { _validateMailOptions(options) {
let { context, email, locale } = options; let { context, email, locale, templateId } = options;
if (!templateId) {
throw new Error('Missing templateId');
}
if (!context) { if (!context) {
throw new Error('Missing context'); throw new Error('Missing context');
} }
@ -57,9 +65,9 @@ class TemplateSender {
if (typeof email === 'string') { if (typeof email === 'string') {
email = email.split(','); email = email.split(',');
} }
if (email.length > this.maxMails) { if (email.length > options.maxMails) {
throw new Error( throw new Error(
`Cannot send more than ${this.maxMails} emails at once` `Cannot send more than ${options.maxMails} emails at once`
); );
} }
if (!locale) { if (!locale) {

View file

@ -299,13 +299,13 @@ router.postAsync('/templates/:templateId/send', async (req, res) => {
try { try {
const templateSender = new TemplateSender({ const templateSender = new TemplateSender({
context: req.context,
locale: req.locale,
templateId: req.params.templateId templateId: req.params.templateId
}); });
const info = await templateSender.send({ const info = await templateSender.send({
context: req.context,
data: input.DATA, data: input.DATA,
email: input.EMAIL, email: input.EMAIL,
locale: req.locale,
sendConfigurationId: input.SEND_CONFIGURATION_ID, sendConfigurationId: input.SEND_CONFIGURATION_ID,
subject: input.SUBJECT, subject: input.SUBJECT,
variables: input.VARIABLES variables: input.VARIABLES