2019-03-24 12:27:56 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const mailers = require('./mailers');
|
2019-04-02 13:15:35 +00:00
|
|
|
const tools = require('./tools');
|
2019-03-24 12:27:56 +00:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
|
|
|
async send(options) {
|
|
|
|
this._validateMailOptions(options);
|
|
|
|
|
|
|
|
const [mailer, template] = await Promise.all([
|
2019-03-31 12:50:40 +00:00
|
|
|
mailers.getOrCreateMailer(options.sendConfigurationId),
|
2019-04-02 11:38:12 +00:00
|
|
|
templates.getById(options.context, this.templateId, false)
|
2019-03-24 12:27:56 +00:00
|
|
|
]);
|
|
|
|
|
2019-04-02 13:15:35 +00:00
|
|
|
const html = tools.formatTemplate(
|
2019-03-24 12:27:56 +00:00
|
|
|
template.html,
|
2019-04-02 13:15:35 +00:00
|
|
|
null,
|
|
|
|
options.variables,
|
|
|
|
true
|
2019-03-24 12:27:56 +00:00
|
|
|
);
|
2019-04-02 13:15:35 +00:00
|
|
|
const subject = tools.formatTemplate(
|
2019-04-02 11:38:12 +00:00
|
|
|
options.subject || template.description || template.name,
|
|
|
|
options.variables
|
|
|
|
);
|
2019-03-24 12:27:56 +00:00
|
|
|
return mailer.sendTransactionalMail(
|
|
|
|
{
|
|
|
|
to: options.email,
|
2019-04-02 11:38:12 +00:00
|
|
|
subject
|
2019-03-24 12:27:56 +00:00
|
|
|
},
|
|
|
|
{
|
|
|
|
html: { template: html },
|
2019-04-02 11:38:12 +00:00
|
|
|
data: options.data,
|
2019-03-24 12:27:56 +00:00
|
|
|
locale: options.locale
|
|
|
|
}
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
_validateMailOptions(options) {
|
2019-03-31 12:50:40 +00:00
|
|
|
let { context, email, locale } = options;
|
2019-03-24 12:27:56 +00:00
|
|
|
|
2019-03-31 12:50:40 +00:00
|
|
|
if (!context) {
|
|
|
|
throw new Error('Missing context');
|
|
|
|
}
|
2019-03-24 12:27:56 +00:00
|
|
|
if (!email || email.length === 0) {
|
|
|
|
throw new Error('Missing email');
|
|
|
|
}
|
|
|
|
if (typeof email === 'string') {
|
|
|
|
email = email.split(',');
|
|
|
|
}
|
|
|
|
if (email.length > this.maxMails) {
|
|
|
|
throw new Error(
|
|
|
|
`Cannot send more than ${this.maxMails} emails at once`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
if (!locale) {
|
|
|
|
throw new Error('Missing locale');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = TemplateSender;
|