简体   繁体   中英

Rest Api Parameter Validation best Practice

Im a bit confused about the Parameter Validation in a node.js Rest Api. I wrote a little Middleware which switch through all routes like this

switch (req.route.path) {
  case '/checkRequirements':
    req.assert('location', 'Invalid Location Array').notEmpty()
    req.assert('platform', 'Invalid Platform').notEmpty()
    req.assert('version', 'Invalid Version').notEmpty()
    break

  case 'login':
    req.assert('uuid', 'Invalid UUID').notEmpty().isUUID()
    req.assert('fbToken', 'Invalid Facebook Token').notEmpty()
    req.assert('location', 'Invalid Location Array').notEmpty()
    break
}

if the the validation pass it goes with next to the api function. But my Co Worker told me i should not do it like this. Instead i should add the validation in the route function it self. He said we should do it like this cause of Latency. Is there a best practice for this situation?

It would be better to do this sort of validation in each corresponding route function. It's more maintainable, since all logic is in one place. Otherwise, if you change a route function, you need to remember to go and update your middleware.

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