restify regular expression on named parameter

2019-09-04 07:07发布

I am using the restify 2.8.4.

Understood that named parameter with regular expression is not supported in Mixing regex and :params in route #247

Instead of cobble both logics into one block.

server.get ('/user/:id', function (req, res, next) {
  var id = req.params.id; 
  // check with isNaN()
  // if string do this
  // if number do that
}

I prefer below code structure:

//hit this route when named param is a number
server.get (/user\/:id(\\d+)/, function (req, res, next) {
  var id = req.params.id; 
  // do stuff with id
}

//hit this route when named param is a string
server.get (/user\/:name[A-Za-z]+/, function (req, res, next) {
  var name = req.params.name; 
  // do stuff with name
}

Is there a way I can split them into two separate concerns?

标签: restify
1条回答
你好瞎i
2楼-- · 2019-09-04 07:57

It looks like you have mostly already done it yourself. Just remove the identifiers from your route and make sure you use regex capture groups.

//hit this route when named param is a number
server.get (/user\/(\d+)/, function (req, res, next) {
    var id = req.params[0]; 
    // do stuff with id
}

//hit this route when named param is a string
    server.get (/user\/([A-Za-z]+)/, function (req, res, next) {
    var name = req.params[0]; 
    // do stuff with name
}

Answer edited to incorporate Cheng Ping Onn's input.

查看更多
登录 后发表回答