Can express.js req and res variables be improved without using middleware feature?

I am working in restful service mode using express.js and I want to improve the req and res variables so that for example you can write something like

app.use(function (req, res, next) {
    res.Ok = function (data) {
        res.status(200).send(data);
    };

    res.InternalError = function (err) {
        res.status(500).send(err);
    };
});

      

And later

router.get('/foo', function (req, res) {
    res.Ok('foo');
})

      

This will send 'foo' to the response body and set the status code to 200 and works great.

My first question is, is it possible to add such functionality without a middleware function, say in the property or prototype of the app variable ?

Second question: if there are performance issues if you add a lot of functionality with application-level middleware functionality. Are these functions bound to the request and response object or once upon application startup?

I know the Sails framework already does this, but I'm wondering if they also use middleware functionality.

+3


source to share


2 answers


I keep digging and it turns out that the request and response object is exposed in express using the property __proto__

.

var express = require('express'),
app = express();

app.response.__proto__.foo = function (data) {
    this.status(200).send(data);
};

      

And later in the router



router.get('/foo', function (req, res, next) {
    res.foo('test');
});

      

This will check the test in your browser so that functionality can be added without using middleware.

Note. I'm sure there are some downsides to this approach (like rewriting predefined properties), but for testing purposes and adding very simple functionality, I find it somewhat better from a performance standpoint.

0


source


I don't know of any other way other than using middleware. But in my opinion you could do the following to achieve pretty much the same.



// Some Route
router.get('/foo', function(req, res, next) {
 // ...
 if(err) {
   res.status(500);
   return next(err);
 }
 return res.send('ok');
});

// Another route
router.get('/bar', function(req, res, next) {
  // ...
  if(badUserId) {
    res.status(400);
    return next('Invalid userId.');
  }
  req.result = 'hello';
  return next();
});

router.use(function(req, res) {
  // I prefer to send the result in the route but an
  // approach like this could work
  return res.send(req.result);
});

// Error Middleware
router.use(function(err, req, res, next) {
  if(res.statusCode === 500) {
    // Log the error here
    return res.send('Internal server error');
  } else {
    return res.send(err);
  }
});

      

0


source







All Articles