简体   繁体   中英

Generic route handlers for express

I am trying to make some generic handlers for REST style routes in an Express app.

They are defined in an object which is then merged with properties defined in specific route files. The merging of properties is working fine. The issue I have is in somehow passing my Model object into the handler's anonymous function.

The code below is the clearest attempt showing what I'm trying to do, but obviously fails as Model is lost in the anonymous function's scope.

/**
 * 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)
    }
}

I've looked at a few options, and still quite new to Node/Express and Connect middleware, so there may be something more obvious I am missing.

I solved the issue by simply calling 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)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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