How to decorate application methods in express?

I am using node.js and am expressing v4.12. I want to decorate all calls with app.get

custom logic.

app.get(/*getPath*/, function (req, res, next) {
    // regular logic
});

      

and my custom logic

customFunc() {
 if (getPath === 'somePath' && req.headers.authorization === 'encoded user'){
       //costum logic goes here
       next();
    } else {
       res.sendStatus(403);
    }     
}

      

The idea is to execute custom logic in front of the code I already have, but I need access to objects req

, res

and next

inside my custom function. And one more problem that I need to have app.get arguments to work with the requested template inside custumFunc. I tried to implement the decorator pattern like this:

var testfunc = function() {
    console.log('decorated!');
};

var decorator = function(f, app_get) {
    f();
    return app_get.apply(this, arguments);
};
app.get = decorator(testfunc, app.get);

      

But javascript throws an error.

EDIT In case app.use()

I can only get the req.path for example /users/22

, but when I use it like app.get('/users/:id', acl, cb)

I can get the property req.route.path

and it is equal '/users/:id'

and this is what I need for my ACL decorator. But I don't want to call a function acl

for each endpoint and try to move it to app.use () but with an attribute req.route.path

.

+3


source to share


2 answers


An example of middleware implementation :

app.use(function(req, res, next) {
 if (req.path==='somePath' && req.headers.authorization ==='encoded user'){
       //costum logic goes here
       next();
    } else {
       res.sendStatus(403);
    }  
});

      



If you only want to pass middleware in one route, you can implement it like this:

app.get(/*getPath*/, customFunc, function (req, res, next) {
    // regular logic
});

      

+2


source


You are trying to create middleware . Just add your decorator to your application via app.use

.



+2


source







All Articles