/ #Node #JavaScript 

Why you should wrap your (JavaScript) dependencies

An email sending example.

Table of Contents

This was sent out on the Code with Hugo newsletter. Subscribe to get the latest posts right in your inbox (before anyone else).

Example using SendGrid

On a very basic level, we want to be able to send emails.

In code terms, we want a send function. What’s nice to have is a way to abstract the message creation, that’s a makeMailMessage function.

See the following code:

const sgMail = require('@sendgrid/mail');

const {
  SENDGRID_API_KEY,
  EMAIL_OVERRIDE_TO_ADDRESS,
  EMAIL_FROM_ADDRESS
} = process.env;

sgMail.setApiKey(SENDGRID_API_KEY);

function makeMailMessage ({
  to,
  from = EMAIL_FROM_ADDRESS,
  subject,
  text,
  html
}) {
  return {
    to: EMAIL_OVERRIDE_TO_ADDRESS || to,
    from,
    subject,
    ...(html ? { html } : { text })
  };
}
function send (message) {
  return sgMail.send(message);
}
module.exports = {
  makeMailMessage,
  send
};

How do we consume this?

async function doSomeSending(name, email) {
  const message = makeMailMessage({
    from: '[email protected]',
    to: email,
    subject: 'Welcome to Code with Hugo',
    text: `Hi ${name}, welcome to Code with Hugo.`
  });
}

Switching to another email provider

Say we want to switch to another provider, namely Mailgun. Ideally, we don’t want to change any of the application code.

const {
  MAILGUN_API_KEY,
  EMAIL_DOMAIN,
  EMAIL_OVERRIDE_TO_ADDRESS,
  EMAIL_FROM_ADDRESS
} = process.env;
const mailgun = require('mailgun-js')({
  apiKey: MAILGUN_API_KEY,
  domain: EMAIL_DOMAIN
});

function makeMailMessage ({
  to,
  from = EMAIL_FROM_ADDRESS,
  subject,
  text,
  html
}) {
  return {
    to: EMAIL_OVERRIDE_TO_ADDRESS || to,
    from,
    subject,
    ...(html ? { html } : { text })
  };
}
function send (message) {
  return new Promise((resolve, reject) => {
    mailgun.messages().send(message, (error, body) => {
      if (error) {
        return reject(error);
      }
      resolve(body);
    });
  });
}

module.exports = {
  makeMailMessage,
  send
};

The API for our mail module stays the same, but we’ve changed the provider under the hood 👍 .

unsplash-logoSamuel Zeller

Looking for a new job? Take Triplebyte’s quiz and have top tech companies pitch you!

Author

Hugo Di Francesco

A Software Engineer and recovering Frontend Engineer who is big on Node.js, queues and Vue(s). He shares practical JavaScript tips for the developer who wants to get things done on Code with Hugo. University College London (UCL), MEng Mathematical Computation Graduate.

Subscribe for Enterprise Node.js and JavaScript Guides

Build your web platform with modern Node.js/JavaScript best-practices, tools and patterns