From 8b39a101cd312d1869c038e432e24048267b1db1 Mon Sep 17 00:00:00 2001 From: Alexey Zinkevych Date: Tue, 2 Apr 2019 16:35:57 +0300 Subject: [PATCH] Transactional mail: minor template-sender refactoring --- server/.eslintrc | 2 +- server/lib/template-sender.js | 34 +++++++++++++++++++++------------- server/routes/api.js | 4 ++-- 3 files changed, 24 insertions(+), 16 deletions(-) diff --git a/server/.eslintrc b/server/.eslintrc index 360c05cb..3cf464f1 100644 --- a/server/.eslintrc +++ b/server/.eslintrc @@ -1,4 +1,4 @@ { "extends": "nodemailer", - "parserOptions": { "ecmaVersion": 2017 } + "parserOptions": { "ecmaVersion": 2018 } } diff --git a/server/lib/template-sender.js b/server/lib/template-sender.js index 0413dfe5..bcbd4db5 100644 --- a/server/lib/template-sender.js +++ b/server/lib/template-sender.js @@ -5,21 +5,26 @@ const tools = require('./tools'); const templates = require('../models/templates'); class TemplateSender { - constructor({ templateId, maxMails = 100 } = {}) { - if (!templateId) { - throw new Error('Cannot create template sender without templateId'); - } - - this.templateId = templateId; - this.maxMails = maxMails; + constructor(options) { + this.defaultOptions = { + maxMails: 100, + ...options + }; } - async send(options) { + async send(params) { + const options = { ...this.defaultOptions, ...params }; this._validateMailOptions(options); const [mailer, template] = await Promise.all([ - mailers.getOrCreateMailer(options.sendConfigurationId), - templates.getById(options.context, this.templateId, false) + mailers.getOrCreateMailer( + options.sendConfigurationId + ), + templates.getById( + options.context, + options.templateId, + false + ) ]); const html = tools.formatTemplate( @@ -46,8 +51,11 @@ class TemplateSender { } _validateMailOptions(options) { - let { context, email, locale } = options; + let { context, email, locale, templateId } = options; + if (!templateId) { + throw new Error('Missing templateId'); + } if (!context) { throw new Error('Missing context'); } @@ -57,9 +65,9 @@ class TemplateSender { if (typeof email === 'string') { email = email.split(','); } - if (email.length > this.maxMails) { + if (email.length > options.maxMails) { throw new Error( - `Cannot send more than ${this.maxMails} emails at once` + `Cannot send more than ${options.maxMails} emails at once` ); } if (!locale) { diff --git a/server/routes/api.js b/server/routes/api.js index 69a6b10b..ebb822e4 100644 --- a/server/routes/api.js +++ b/server/routes/api.js @@ -299,13 +299,13 @@ router.postAsync('/templates/:templateId/send', async (req, res) => { try { const templateSender = new TemplateSender({ + context: req.context, + locale: req.locale, templateId: req.params.templateId }); const info = await templateSender.send({ - context: req.context, data: input.DATA, email: input.EMAIL, - locale: req.locale, sendConfigurationId: input.SEND_CONFIGURATION_ID, subject: input.SUBJECT, variables: input.VARIABLES