Growing a API modularly with Node

This week I started a new gig at Mombo Labs. Lucky for me I finally get to work with some of the technologies I have been interested in for the last year or so as my day job. To get my feet wet and get elbow deep in our codebase, I started exploring our server API by creating a wrapper library for node.js.

EdTjP

Once I got started, I realized that the API has a pretty big surface area dealing with authentication, user CRUD and various domain concepts. I wanted to create a simple entry point for my API but also divide up my code based on domain topic.

I started out creating a constructor for my API that basically sets up some private members and loads up the request module along with some helper functionality around creating endpoint Uris. This code lives in my modules index.js entry point.

'use strict';

var url = require('url');

var Api = exports.Api = function(protocol, host, port, email, password) {
    this.protocol = protocol;
    this.host = host;
    this.port = port;
    this.user_email = email;
    this.user_password = password;
    this.token = '';

    this.request = require('request');

    this.makeUri = function(path) {
        var basePath = 'webexp/';

        return url.format({
            protocol: this.protocol,
            hostname: this.host,
            port: this.port,
            pathname: basePath + path
        });
    };
};

I then wanted to deal with authentication so I created a modules folder next to my index.js and added a authentication.js file. This script basically exports a function that monkey patches an authenticate method on to the scope of the function executor.

'use strict';

module.exports = function(){
    
    this.authenticate = function(email, password, callback) {
        if(typeof email === 'function') callback = email;
        var scope = this;
        var authentication_options = {
            url: this.makeUri('LoginUser'),
            body: JSON.stringify({
                email: this.user_email || email,
                password: this.user_password || password}),
            json: true
        };

        this.request(authentication_options, function(err, res, body){
            scope.token = body.token = res.headers['x-token'];
            callback(err, body);
        });
    };
};

I can now return to my index.js and add a simple require statement like this, to apply my authentication methods to my API object.

require('./modules/authentication').call(Api.prototype);

In case it is not clear, here is a shot of what my project structure looks like.

EdTjP

Follow me on Mastodon!