繁体   English   中英

快递的通用路线处理程序

[英]Generic route handlers for express

我正在尝试为Express应用程序中的REST样式路由创建一些通用处理程序。

它们在一个对象中定义,然后与特定路由文件中定义的属性合并。 属性的合并工作正常。 我遇到的问题是以某种方式将我的Model对象传递到处理程序的匿名函数中。

下面的代码是最清晰的尝试,显示了我要执行的操作,但是由于Model在匿名函数的作用域中丢失,因此显然失败了。

/**
 * Model is a Mongoose model object
 */
routeDefinitions: function (resourceName, Model) {
    routePath = api_prefix + resourceName.toLowerCase();

    var routeProperties = {
        getById: {
            method: 'get',
            isArray: false,
            auth: true,
            url: routePath + '/:id',
            handlers: [function (req, res, next) {
                Model.findById(req.param('id')).exec(res.handle(function (model) {
                    console.log(model);
                    res.send(model);
                }));
            }]
        },
        getAll: {
            method: 'get',
            isArray: true,
            auth: true,
            url: routePath,
            handlers: [function (req, res, next) { 
                Model.find().exec(res.handle(function (model) {
                    res.send(model);
                }));        
            }]
        },
        //... (create, update, delete etc)
    }
}

我已经研究了一些选项,但是对于Node / Express和Connect中间件来说还是很新的东西,因此可能缺少一些更明显的东西。

我通过简单地调用mongoose.model解决了这个问题:

routeDefinitions: function (resourceName) {
    routePath = api_prefix + resourceName.toLowerCase();
    var modelName = inflect.singularize(resourceName);
    var Model = mongoose.model(modelName);

    var routeProperties = {
        getById: {
            method: 'get',
            isArray: false,
            auth: true,
            url: routePath + '/:id',
            handlers: [function (req, res, next) {
                Model.findById(req.param('id')).exec(res.handle(function (model) {
                    console.log(model);
                    res.send(model);
                }));
            }]
        },
        getAll: {
            method: 'get',
            isArray: true,
            auth: true,
            url: routePath,
            handlers: [function (req, res, next) { 
                Model.find().exec(res.handle(function (model) {
                    res.send(model);
                }));        
            }]
        },
        //... (create, update, delete etc)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM