import { DataSource } from 'apollo-datasource'; import sendgrid from '@sendgrid/mail'; import logger from '@/logger'; import { DEFAULT_SEND_OPTIONS, SendOptions } from './types'; export default class TransactionalEmailSender extends DataSource { private enabled: boolean; constructor() { super(); const apiKey = process.env.SENDGRID_API_KEY; // never enable in tests const enabled = !!process.env.EMAIL_SENDING_ENALBED && process.env.NODE_ENV !== 'test'; if (enabled) { if (!apiKey) { throw new Error( 'Cannot start TransactionalEmailSender without SENDGRID_API_KEY in environment' ); } else { sendgrid.setApiKey(apiKey); } } this.enabled = enabled; } async send(input: SendOptions): Promise { const { to, from, subject, text, html } = { ...DEFAULT_SEND_OPTIONS, html: input.text.replace(/\n/g, '
'), ...input, }; const payload = { to, from, subject, text, html, }; if (this.enabled) { await sendgrid.send(payload); } else { logger.info('Email sending disabld. Message that would have been sent:'); logger.info( Object.entries(payload).reduce((prev, [key, value]) => { return `${prev}${key.toUpperCase()}: ${value}\n`; }, '') ); } } }