1

I'm using nodejs Express. I would like to have a router that receive id or username as request param as below:

router.get('/:id?/:username?', authMiddleware, function (req, res, next) {
    models
    .User
    .findAll({
        where: {
            $or: {
                id: req.params['id'],
                username: req.params['username']
            }
        }
    })
    .then(function (rows) {
        res.send(rows);
    })
}

However, express seems to not understand my request on: http://localhost:3000/api/1.0/users//david

Which I would like to query user by username instead of id

The only way works right now is defining a route as: /:id_or_username as below:

router.get('/:id_or_username', function (req, res, next) {
    models
    .User
    .findAll({
        where: {
            $or: {
                id: req.params['id_or_username'],
                username: req.params['id_or_username']
            }
        }
    })
    .then(function (rows) {
        res.send(rows);
    })
}

But it is kind of dirty and I'm not happy with that code. Is that possible to define router in this case using REST style instead of :idOrName param?

  • If your `id` is an `Int` you could check if the param is an `Int` and search by `id` if not then search by `username`. – sbarow Mar 11 '16 at 19:22

2 Answers2

1

I am not sure how your system is setup but this sounds like a better use for a req.query instead of req.param.

You should use req.query when you are not sure what the input might be, and use req.param when passing information you are sure will be there. There is probably a way to do this with req.param but I am not sure I can think of a reason why you'd want to do it that way.

This way you could do an action like:

action = "/users/"+ id ? id : username

and then req.query for it.

Morgan G
  • 3,089
  • 4
  • 18
  • 26
  • Hi Morgan, it is only api which there still have no UI yet. I want it to support something like below: Get by ID: /api/1.0/users/id_as_integer Get by ID or Name: /api/1.0/users/id_as_integer/username_as_string Get by Name: /api/1.0/users//username_as_string (/api/1/0.users//username_as_string) – Le Huu HoangGia Mar 12 '16 at 10:22
1

Assuming your id is an int, you can do something like this:

router.get('/:id_or_username', function (req, res, next) {
    var where = {}
    var param = req.params['id_or_username']

    if (isNaN(param)) {
      where.username = param
    } else {
      where.id = param
    }
    models.User.findAll({where}).then(function (rows) {
        res.send(rows)
    })
}

Now you can send the id or the username using the same paramether

emilioriosvz
  • 1,629
  • 1
  • 19
  • 30