Callum Linington
Callum Linington

Reputation: 14417

Node Js Module Layering

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

Upvotes: 0

Views: 82

Answers (1)

adeneo
adeneo

Reputation: 318182

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');
        }
    }
}

Upvotes: 1

Related Questions