将对象转换为表达动态路由

时间:2013-09-30 14:13:09

标签: node.js express routing

我有一个看起来像的对象:

{
    api: {
        test: function () {}
    },
    routes: {
        docs: {
            options: function () {},
            usage: function () {}
        },
        index: function () {},
        bugs: {
            report: function () {}
        }
    }
}

这是一个通过遍历目录树来映射我的应用程序控制器的对象,并且如果有文件则需要dir中的每个文件。该文件返回module.exports函数。

我正在尝试做的是快递中有以下路由:

application.get("/", controllers.routes.index);
application.get("/partials/index", controllers.routes.partials.index);
application.get("/partials/documentation/amd", controllers.routes.partials.documentation.amd);
application.get("/partials/documentation/api", controllers.routes.partials.documentation.api);
application.get("/partials/documentation/jquery", controllers.routes.partials.documentation.jquery);
application.get("/partials/documentation/options", controllers.routes.partials.documentation.options);
application.get("/partials/documentation/usage", controllers.routes.partials.documentation.usage);
application.get("/partials/installation/bower", controllers.routes.partials.installation.bower);
application.get("/partials/installation/source", controllers.routes.partials.installation.source);
application.get("/partials/compatibility/methods", controllers.routes.partials.compatibility.methods);
application.get("/partials/compatibility/support", controllers.routes.partials.compatibility.support);
application.get("/partials/bugs/requests", controllers.routes.partials.bugs.requests);
application.get("/partials/bugs/report", controllers.routes.partials.bugs.report);
application.get("*", controllers.routes.index);

以某种方式动态而不是硬编码每一个。我无法弄清楚这样做的逻辑,我想做的事情如下:

var keys = Object.keys(controllers), //where controllers is my object containing the routes and api, what I just wrote one block of code above
    length = keys.length - 1;

while (length >= 0) {
    ... something that will check the object if it will contain any other object and will do a recursive iteration, then will somehow concatenate the parent object keys ...
}

我不确定如何获得子对象的所有父键(类似routes docs options),因为这是我实际需要组成传递给express的路由字符串。

1 个答案:

答案 0 :(得分:1)

像这样(http://jsfiddle.net/trevordixon/hym76/):

function registerRoutes(path, routes, level) {
    var level = level || 0;

    for (var p in routes) {
        if (typeof routes[p] === 'function') {
            if (p === 'index' && level === 0) app.get(path, routes[p]);
            else app.get(path + p, routes[p]);
        } else {
            // Recursive call; adds ancestors to the path with each call
            registerRoutes(path + p + '/', routes[p], level+1);
        }
    }
}

registerRoutes('/', controllers.routes);
registerRoutes('/api/', controllers.api);