Friday 2 June 2017

Express.js - wrap every middleware/route in "decorator"

I have Express.js instance and couple of routes which I want to wrap in some function. Example:

const wrapper = (route) => {
  return (req, res, next) => {
    let result = route(req, res, next);

    // do some independent processing
  }
};

app.get('/', wrapper((req, res, next) => {
  // respond to request somehow
}));

While this works fine, I don't like the idea to explicitly call wrapper on every route or middleware which requires such processing.

Is there any way to be able to wrap every required route/middleware in certain wrapper (given that wrapper function can check that this route/middleware needs to be wrapped) implicitly (via Express.js extension, monkey-patching or some special middleware)?



via Kid Binary

No comments:

Post a Comment