Created
August 1, 2023 21:54
-
-
Save gkobilansky/d9a3e80f0175479be6431dc7f52b8600 to your computer and use it in GitHub Desktop.
Email Service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@nestjs/common'; | |
import * as sgMail from '@sendgrid/mail'; | |
import * as Sentry from '@sentry/node'; | |
import { PRODUCTION_ENV_NAME, DOMAIN_AND_EMAIL_WHITE_LIST } from '../settings'; | |
const templateIds = { | |
programPurchase: 'd-e8cd31b0131a48bba6041692ed38c9f6', | |
injuryMarked: 'd-ccef4e3e556f42ee8e5750b9a0009d37', | |
}; | |
const domains = { | |
local: 'http://localhost:4000', | |
dev: 'https://dev.app.gmb.io', | |
stage: 'https://stage.app.gmb.io', | |
production: 'https://app.gmb.io', | |
}; | |
const getDomain = (domainList: { [domain: string]: string }) => { | |
return domainList[process.env.NODE_ENV] || domainList.dev; | |
}; | |
@Injectable() | |
export class EmailService { | |
private fromEmail: string = process.env.EMAIL_FROM_ADDRESS; // e.g 'GMB Fitness <howdy@gmb.io>'; | |
readonly defaultSettings; | |
constructor() { | |
sgMail.setApiKey(process.env.SENDGRID_API_KEY); | |
this.defaultSettings = { | |
from: this.fromEmail, | |
}; | |
} | |
async sendInjury(to, params: { firstName: string }): Promise<any> { | |
const settings = { | |
to, | |
templateId: templateIds.injuryMarked, | |
dynamic_template_data: { | |
host: getDomain(domains), | |
firstName: params.firstName, | |
}, | |
}; | |
return this.send(settings); | |
} | |
async send(settings): Promise<any> { | |
try { | |
if (process.env.NODE_ENV !== PRODUCTION_ENV_NAME) { | |
const subscribersDomain = settings.to.split('@')[1]; | |
if ( | |
!( | |
DOMAIN_AND_EMAIL_WHITE_LIST.includes(subscribersDomain) || | |
DOMAIN_AND_EMAIL_WHITE_LIST.includes(settings.to) | |
) | |
) { | |
Sentry.addBreadcrumb({ | |
message: 'Email sending is disabled by `DOMAIN_WHITELIST` environment variable.', | |
}); | |
return; | |
} | |
} | |
await sgMail.send(Object.assign({}, this.defaultSettings, settings)); | |
} catch (e) { | |
Sentry.captureMessage(e, { level: Sentry.Severity.Error }); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment