Adapting The Azure Queue API For Node.js

Thursday, April 3, 2014

The Azure SDK for Node.js is feature rich and comprehensive, but there is always room to provide some additional abstraction and tailor an API to make it easier to use inside a specific application.

For example, imagine we need to the ability to get a single messages from an Azure queue, and also delete a single message. Here is a module that can expose a custom API for use in a bigger application. As a bonus, the module adapts the API to use promises instead of callbacks.

var Q = require("Q");
var azure = require("azure");

module.exports = function(config) {

    var retryOperations = new azure.ExponentialRetryPolicyFilter();
    var queueService = azure.createQueueService(config.storageName, config.storageKey)
                            .withFilter(retryOperations);
    var singleMessageDefaults = { numofmessages: 1, visibilitytimeout: 2 * 60 };

    var getSingleMessage = function() {
        var deferred = Q.defer();
        queueService.getMessages(config.queueName, singleMessageDefaults,
                                 getSingleMessageComplete(deferred));
        return deferred.promise;
    };

    var deleteMessage = function(message) {
        var deferred = Q.defer();        
        queueService.deleteMessage(config.queueName, message.messageid,
                                   message.popreceipt, deleteComplete(deferred));
        return deferred.promise;
    };

    var getSingleMessageComplete = function(deferred) {
        return function(error, messages) {
            if (error) {
                deferred.reject(error);
            } else {
                if (messages.length) {
                    deferred.resolve(messages[0]);
                } else {
                    deferred.resolve();
                }
            }
        };
    };

    var deleteComplete = function(deferred) {
        return function(error) {
            if (error) {
                deferred.reject(error);
            } else {
                deferred.resolve();
            }
        };
    };

    return {
        getSingleMessage: getSingleMessage,
        deleteMessage: deleteMessage
    };
};

The configuration can live in a simple .json file.

{
    "storageName": "name",
    "storageKey": "qY5Qk...==",    
    "tableName": "patients",
    "queueName": "exportrequests"
}

And now checking the queue is easy.

var config = require("./config.json");
var queue = require("./queue")(config);

queue.getSingleMessage()
     .then(processMessage)
     .catch(processError);

Next up, we’ll see how to use this code from Node.js inside a continuously running Azure WebJob.


Comments
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!