Build a Backend With Node.js, Container and Azure (3)

In the last post, We have created an API that accepts registration request, saves user information into the database. Once a registration is completed, we want to send a welcome email to the user. Sending email is a time-consuming task, it should be done asynchronously outside the user request/response cycle. This enables web requests to return immediately, results in better response time and higher throughput.

Email worker

In this post we are going to create an email worker that runs in a separate process, pulls tasks from the message queue and sends emails.

var config = require('./config/config')
var nodemailer = require('nodemailer');

var EmailService = require('./src/email_service')

function handleError()  {
    this.close();
    setTimeout( function() {
        processor = start_worker();
    }
    , 10000)
}

function onMessage(data) {
    var email_address = data;
    var transporter = nodemailer.createTransport( {
        service: config.email.service ,
        auth: {
            user: config.email.user, // Your email id
            pass: config.email.pass  // Your password
        }
    });

    var mailOptions = {
        from: config.email.from, 
        to: email_address, 
        subject: 'Welcome!', 
        html: '<b>Thanks for registering</b>' 
    };

    transporter.sendMail(mailOptions, function(error, info){
        if(error){
            console.log(error);
        }else{
            console.log('Message sent: ' + info.response);
        };
    });
}

function start_worker() {
    var emailProcessor = new EmailService();
    emailProcessor.once('error', handleError.bind(emailProcessor))
    emailProcessor.once('connect', (function() {
            this.process('email', onMessage)
        })
        .bind(emailProcessor) 
    )

    return emailProcessor.start();
}


var processor = start_worker();

We also need to install the nodemailer package which does the real work of email sending.

npm install --save nodemailer

Note that we are using the same repository as api. The EmailService is used by both api and work for message publish/subscribe.

In next post, we will put everything together. Start a dev database, message queue, launch the API server, run the task work.