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.

4

1 回答 1

1

我在编写时遇到了同样的问题snaptun(LokiJS 的 http 服务器包装器,它仍在进行中)。我发现最好的解决方案是创建一个函数,该函数需要一个db参数来生成所有路由(因此db只传递一次并以闭包方式保留)所以在我的 index.js 中我最终得到:

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

自然routes.js需要导出一个函数而不是一个对象。我使用 express,所以在我的情况下,我可以简单地迭代routes数组并以编程方式设置路由。这是包含 WIP 工作的 repo:snaptun

于 2015-08-01T18:13:31.620 回答