0

Given routes

GET /user/42
GET /user/dude

where 42 is user id and dude is username.

So, I want to have method in my controller that return user for both cases. Here it is:

// api/controllers/UserController.js
findOne: function(req, res) {
    User.findOne({
        or: [
            {id: req.params.id},
            {username: req.params.id}
        ]
    }).exec(function(err, user) {
        if (err) {
            return console.log(err);
        }
        res.json(user);
    });
},

When I try to GET /user/42 everything is fine.

When I try to GET /user/dude I get error:

Error (E_UNKNOWN) :: Encountered an unexpected error

error: invalid input syntax for integer: "dude"

It seems like sails refuses to process {id: 'dude'} because of type mismatch.

I am using sails 0.10.5 with sails-postgresql 0.10.9. So what am I doing wrong?

UPD: I do know how to solve problem. Of course I can put if statement to my controller and check what type of parameter it got. Actually, I just created two routes with regexp parameters that point to single method.

My actual problem is why I can not do this with or. Does sails provide such way?

Community
  • 1
  • 1
Boris Zagoruiko
  • 12,705
  • 15
  • 47
  • 79

1 Answers1

1

By default, sails get method only supports id numbers. You will need to define custom routes and implement the relevant api method to support a get request using a string instead of a number.


Technical Details: To solve your exact problem, you need to define the following route in your routes.js

module.exports.routes = {
...
  '/user/get/:param': 'UserController.findByIDorName', 
...
}

This will pass anything after the /user/get/ as the parameter named 'param' to the findByIDorName controller method.

Next you need to check the type of the param and decide if you want to fetch the user info based on the id or the name, so add this function in your userController.js

findByIDorName : function (req, res) {
         if (isNaN(req.param)){
              //find the user by his username after any validation you need
         }
         else {
             //find the user by his id and return
         }
}
arkoak
  • 2,437
  • 21
  • 35
  • I do. I am not using blueprints at all. – Boris Zagoruiko Feb 26 '15 at 12:13
  • I added some details how you need to handle this in the routes and controller. – arkoak Feb 27 '15 at 05:58
  • Thanks for trying. I have upvoted your answer but it does not solve my actual problem. I update question for more details – Boris Zagoruiko Feb 27 '15 at 09:51
  • It seems the sails internal implementation is a bit different for both findOne and populate, but you are going against the laws in populate too :) you should detect the type (validate) and then pass it to the db query so that you do not query an id against a string in any scenario (mayb the next version of sails break the populate too?) – arkoak Feb 27 '15 at 12:45