Skip to content

Commit

Permalink
Refactor MailgunSend#send to use async/await
Browse files Browse the repository at this point in the history
  • Loading branch information
pdroll committed Jan 14, 2021
1 parent 81fbcf6 commit 0e48b63
Showing 1 changed file with 26 additions and 33 deletions.
59 changes: 26 additions & 33 deletions lib/MailgunSend.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,9 @@ class MailgunSend {
* @param {object} creds Object of options for sending an email
* @return {Promise} Promise that will complete when email sends
*/
send(options) {
return new Promise((fulfill, reject) => {
try {
MailgunSend.validate(options);
} catch (e) {
reject(e);
return false;
}
async send(options) {
try {
MailgunSend.validate(options);

const mailOpts = {
from: options.from,
Expand Down Expand Up @@ -100,33 +95,31 @@ class MailgunSend {
mailOpts.bcc = options.bcc;
}

return this.mailgun.messages.create(this.domain, mailOpts)
.then((response) => {
const { id, message } = response;
let successMessage = `\n\t🚀 ✉️ Email was successfully sent to ${options.to}!\n`;

if (options.verbose) {
successMessage += `\n\t🗒 API Message: "${message}"\n\n\t🆔 Message ID: ${id}\n`;
}

fulfill(successMessage);
})
.catch((err) => {
if (err.status === 401) {
reject(new Error(
'\n\t🚫 Your Mailgun API key and/or domain are incorrect.'
const response = await this.mailgun.messages.create(this.domain, mailOpts);

const { id, message } = response;
let successMessage = `\n\t🚀 ✉️ Email was successfully sent to ${options.to}!\n`;

if (options.verbose) {
successMessage += `\n\t🗒 API Message: "${message}"\n\n\t🆔 Message ID: ${id}\n`;
}

return successMessage;
} catch (err) {
if (err.status === 401) {
throw new Error(
'\n\t🚫 Your Mailgun API key and/or domain are incorrect.'
+ '\n\t🔁 Rerun your command with -R flag to re-enter you credentials.',
));
} else if (err.type === 'EUNAVAILABLE') {
reject(new Error(
'\n\t‼️ 🌐 Looks like you may not be connected to the internet. '
);
} else if (err.type === 'EUNAVAILABLE') {
throw new Error(
'\n\t‼️ 🌐 Looks like you may not be connected to the internet. '
+ 'Check your network settings and try again.',
));
} else {
reject(new Error(`\n\t🚫 ${err.message}`));
}
});
});
);
} else {
throw err;
}
}
}
}

Expand Down

0 comments on commit 0e48b63

Please sign in to comment.