0

It is my first node.js app. I use http://www.nodebeginner.org/ as example and http://lokijs.org/ as in-memory db. So, i have problem with code orgatization. Now it is looks like following:

index.js

var server = require('./server');
var router=require('./router');
var reqHandler=require('./handler');

var loki=require('lokijs');
var db = new loki('world.json');

var handle={
    '/getById':reqHandler.getById
};
db.loadDatabase({},function(){
    server.start(router.route, handle,db)
});

server.js

var http = require('http');
var url = require('url');

function start(route,handle,db){
    http.createServer(function (req, res) {
            route(req, res, handle,db);
    }).listen(8080);
}

exports.start=start;

router.js

var url = require('url');

function route(req,res,handle,db) {
    var pathname = url.parse(req.url).pathname;
    if (typeof handle[pathname] === 'function') {
        handle[pathname](res, req,db);
    } else {
        //process error
    }
}

exports.route = route;

handler.js

var url = require('url');
var loki=require('lokijs');
var querystring=require('querystring');

function getById(res, req,db){
    //process req. send response
    //HERE db MUST BE ACCESSIBLE
}

exports.getById=getById;

With current code structure I have to pass db variable from the most begining index.js to the last handler.js. It seems like not brilliant solution for me.

Can anybody help me with it? Thx in advance.

anastsiacrs
  • 159
  • 4
  • 18

1 Answers1

1

I faced the same problem when writing snaptun (a http server wrapper for LokiJS, which is still work-in-progress). I found the best solution to be to create a function that takes a db parameter to generate all the routes (so db is only passed once and retained in a closure fashion) so in my index.js i ended up with:

var db = new loki(file, {
    autoload: false
  }),
  routes = require('./routes')(db);

naturally routes.js needs to export a function not an object. I use express so in my case i could simply iterate the routes array and set routes programmatically. This is the repo that contains the WIP work:snaptun

Joe Minichino
  • 2,793
  • 20
  • 20