Hi everyone, I want to thank this community for the consistent support that it is showing me, and I am back for more.I am currently refactoring the node-express-mysql based backend of a B2B enterprise application, and ran into this debate with my team manager which can be summed up best like this:We have a separate validator module which accepts the request object and using the request path and method , queries an array for the corresponding validation schema and rules, validates the request against these rules using Joi.validate() and based on the error value, call the callback with different parameters. We are not using any middleware as such like express-validation/ express-validator. Right now the validator module is being called from inside the route listener like so:app.post('/path', (req, res) => {async.waterfall([function (cb) {return validate(req, cb);}], (err, results) => {if (err) {// call errorhandler} else if (err === null) {oEntity.create(req, res);}});});Manager and I both agree this is too convoluted and needs to be resolved.My solution, as I have seen at countless places, is definitely get rid of the callback mechanism and directly call the errorHandler from within the validator module, but put the validator in the router call, making the whole code reduce to this:app.post('/path', validate, oEntity.create)My manager would rather prefer writing a middleware in our route index than mentioning the validate in every router where validation is needed , something like thisapp.use(function(req,res,next){validate(req)})app.post('/path',oEntity.create)One of the drawbacks that I can think of immediately is we would need to provide empty validation rules for requests in which no data is being sent from the client, like version or health check endpoints, or a GET call with no parameters in path or query , which is supposed to get all data from a particular entity relevant to the client based on their auth credentials (which we can get from the req.headers; because we are using basic authentication).I would like to know more about the pros and cons of both of these approaches. For now we are moving forward with the manager's approach.
Submitted January 03, 2019 at 03:04PM by enkayjee
No comments:
Post a Comment