Skip to content

Commit

Permalink
feat(preview): Pass options to preview-email
Browse files Browse the repository at this point in the history
  • Loading branch information
leosuncin committed Apr 7, 2020
1 parent 4a2c0d5 commit d0009ce
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
19 changes: 19 additions & 0 deletions lib/interfaces/mailer-options.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,23 @@ export interface MailerOptions {
options?: { [name: string]: any };
};
options?: { [name: string]: any };
preview?:
| boolean
| Partial<{
/**
* a path to a directory for saving the generated email previews
* (defaults to os.tmpdir() from os)
*
* @see https://nodejs.org/api/os.html#os_os_tmpdir
* @type {string}
*/
dir: string;
/**
* an options object that is passed to `open` (defaults to { wait: false })
*
* @see https://github.com/sindresorhus/open#options
* @type {(boolean | { wait: boolean; app: string | string[] })}
*/
open: boolean | { wait: boolean; app: string | string[] };
}>;
}
27 changes: 21 additions & 6 deletions lib/mailer.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/** Dependencies **/
import { get } from 'lodash';
import { get, defaultsDeep } from 'lodash';
import { Injectable, Inject } from '@nestjs/common';
import { createTransport, SentMessageInfo, Transporter } from 'nodemailer';
import * as previewEmail from 'preview-email';
Expand Down Expand Up @@ -29,11 +29,14 @@ export class MailerService {

return templateAdapter.compile(mail, callback, this.mailerOptions);
});
transporter.use('stream', (mail, callback) => {
return previewEmail(mail.data)
.then(() => callback())
.catch(callback);
});

if (this.mailerOptions.preview) {
transporter.use('stream', (mail, callback) => {
return previewEmail(mail.data, this.mailerOptions.preview)
.then(() => callback())
.catch(callback);
});
}
}
}

Expand All @@ -56,6 +59,18 @@ export class MailerService {
'template.adapter',
);

/*
* Preview setup
* THIS NEED TO RUN BEFORE ANY CALL TO `initTemplateAdapter`
*/
if (this.mailerOptions.preview) {
const defaults = { open: { wait: false } };
this.mailerOptions.preview =
typeof this.mailerOptions.preview === 'boolean'
? defaults
: defaultsDeep(this.mailerOptions.preview, defaults);
}

/** Transporters setup **/
if (mailerOptions.transports) {
Object.keys(mailerOptions.transports).forEach((name) => {
Expand Down

0 comments on commit d0009ce

Please sign in to comment.