(Updated: )
/ #node #javascript #es6 

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

Author

Hugo Di Francesco

Co-author of "Professional JavaScript", "Front-End Development Projects with Vue.js" with Packt, "The Jest Handbook" (self-published). Hugo runs the Code with Hugo website helping over 100,000 developers every month and holds an MEng in Mathematical Computation from University College London (UCL). He has used JavaScript extensively to create scalable and performant platforms at companies such as Canon, Elsevier and (currently) Eurostar.

Get The Jest Handbook (100 pages)

Take your JavaScript testing to the next level by learning the ins and outs of Jest, the top JavaScript testing library.