All files / src/utils email.js

100% Statements 23/23
89.47% Branches 17/19
100% Functions 3/3
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 6115x   15x   15x 15x     17x 4x 4x       4x   4x     13x   13x 4x     9x 9x   8x                 8x   8x       17x   13x                   12x 12x     15x  
const nodemailer = require('nodemailer');
 
const FROM_ADDRESS = '"ShyTalk" <noreply@shytalk.shyden.co.uk>';
 
let _transport = null;
let _transportKey = null;
 
function getTransport() {
  if (process.env.NODE_ENV === 'local') {
    Eif (!_transport) {
      _transport = nodemailer.createTransport({
        host: process.env.SMTP_HOST || 'localhost',
        port: Number.parseInt(process.env.SMTP_PORT || '1025', 10),
      });
      _transportKey = 'local';
    }
    return _transport;
  }
 
  const { SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS } = process.env;
 
  if (!SMTP_HOST || !SMTP_USER || !SMTP_PASS) {
    throw new Error('SMTP not configured');
  }
 
  const key = `${SMTP_HOST}:${SMTP_PORT}:${SMTP_USER}:${SMTP_PASS}`;
  if (_transport && _transportKey === key) return _transport;
 
  _transport = nodemailer.createTransport({
    host: SMTP_HOST,
    port: Number.parseInt(SMTP_PORT || '587', 10),
    secure: false,
    auth: {
      user: SMTP_USER,
      pass: SMTP_PASS,
    },
  });
  _transportKey = key;
 
  return _transport;
}
 
async function sendEmail(to, subject, html) {
  const transport = getTransport();
 
  return transport.sendMail({
    from: FROM_ADDRESS,
    to,
    subject,
    html,
  });
}
 
// Exported for test cleanup only
function _resetTransport() {
  _transport = null;
  _transportKey = null;
}
 
module.exports = { sendEmail, _resetTransport };