UNPKG

@nest-modules/mailer

Version:

NestJS - a mailer module (@mailer)

69 lines (68 loc) 3.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const lodash_1 = require("lodash"); const common_1 = require("@nestjs/common"); const nodemailer_1 = require("nodemailer"); const mailer_options_constant_1 = require("./constants/mailer-options.constant"); let MailerService = class MailerService { constructor(mailerOptions) { this.mailerOptions = mailerOptions; this.transporters = new Map(); if ((!mailerOptions.transport || Object.keys(mailerOptions.transport).length <= 0) && !mailerOptions.transports) { throw new Error('Make sure to provide a nodemailer transport configuration object, connection url or a transport plugin instance.'); } const templateAdapter = lodash_1.get(this.mailerOptions, 'template.adapter'); if (mailerOptions.transports) { Object.keys(mailerOptions.transports).forEach(name => { this.transporters.set(name, nodemailer_1.createTransport(this.mailerOptions.transports[name], this.mailerOptions.defaults)); this.initTemplateAdapter(templateAdapter, this.transporters.get(name)); }); } if (mailerOptions.transport) { this.transporter = nodemailer_1.createTransport(this.mailerOptions.transport, this.mailerOptions.defaults); this.initTemplateAdapter(templateAdapter, this.transporter); } } initTemplateAdapter(templateAdapter, transporter) { if (templateAdapter) { transporter.use('compile', (mail, callback) => { if (mail.data.html) { return callback(); } return templateAdapter.compile(mail, callback, this.mailerOptions); }); } } sendMail(sendMailOptions) { return tslib_1.__awaiter(this, void 0, void 0, function* () { if (sendMailOptions.transporterName) { if (this.transporters && this.transporters.get(sendMailOptions.transporterName)) { return yield this.transporters .get(sendMailOptions.transporterName) .sendMail(sendMailOptions); } else { throw new ReferenceError(`Transporters object doesn't have ${sendMailOptions.transporterName} key`); } } else { if (this.transporter) { return yield this.transporter.sendMail(sendMailOptions); } else { throw new ReferenceError(`Transporter object undefined`); } } }); } }; MailerService = tslib_1.__decorate([ common_1.Injectable(), tslib_1.__param(0, common_1.Inject(mailer_options_constant_1.MAILER_OPTIONS)), tslib_1.__metadata("design:paramtypes", [Object]) ], MailerService); exports.MailerService = MailerService;