Node Js Module Layering

Node Js Module Layering

Problem

If you had a server js like so:

var app = require('express'),
    http = require('http'),
    news = require('./server/api/news'),
    db = require('mongoose');

/* app config..... */
app.get('/api/news', news.list);


var server = http.createServer(app);
server.listen(app.get('port'), function () {
    console.log("Server running");
});

And I wanted to create an API to handle adding news items to the database:

var db = require('mongoose');

/*** Public Interfaces ***/
function list(req, res) {
    var offset = ~~req.query.offset || 0,
        limit = ~~req.query.limit || 25;

    db.News.find(function (err, newsItems) {
        res.json(newsItems.slice(offset*limit, offset*limit + limit));
    });   
}

exports.list = list;

This API would exist in its own file, how do I use the instance of the db created in the server.js inside the new module.

Or do you create and open a new connection each time you query the database?

Thanks

Problem courtesy of: Callum Linington

Solution

I would probably do it more like this

the server :

var express = require('express'),
    app     = express(),
    http    = require('http'),
    db      = require('mongoose'),
    news    = require('./server/api/news')(db); // you can pass anything as args

app.get('/api/news', news.list);
/* add routes here, or use a file for the routes */
// app.get('/api/morenews', news.more_news); .... etc

http.createServer(app).listen(8000);

and in the ../news/index.js file or whatever you’re using, I’d use a literal, but you can always use exports to pass back each method as well

module.exports = function(db) {
    /* now db is always accessible within this scope */
    return {
        list : function (req, res) {
            var offset = ~~req.query.offset || 0,
                limit = ~~req.query.limit || 25;

            db.News.find(function (err, newsItems) {
                res.json(newsItems.slice(offset*limit, offset*limit + limit));
            });
        }, // now you can easily add more properties
        more_news : function(req, res) {
            res.end('Hello kitty');
        }
    }
}
Solution courtesy of: adeneo

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *