user1345112
user1345112

Reputation: 342

sails.js - unique model attribute check

Project: API over websockets (socket.io)

My goal: check if a username is unique before storing it

My solution: Overwrite default createUser function

My problem: calling User:create doesn't do the validation

code in the user controller:

create: function(req, res, next){
    User.findByUsername(req.param('username')).then(function(usr){
             if(usr !='')
            {
                // username already taken
                return res.json({'type':'validationError','errorMessage':'Username already taken','usr':usr});
            }
            else{
                // username is unique
                User.create( req.params.all(),function userCreated(err,user){
                    // try to create user
                    if(err){
                        console.log(err);
                        return res.json({
                                'type':'validationError',
                                'errorMessage':err}
                        );
                    }
                    res.json(user);
                });
            }
        },
        function(err){
            // error finding user by username
        }
    );

Upvotes: 3

Views: 437

Answers (1)

brittonjb
brittonjb

Reputation: 502

I believe approaching the problem in a slightly different way could potentially make this easier for you. You can handle the validation in the model:

attributes: {
  username: {
    type: 'string',
    unique: true
  }
}

Then, without overriding anything in the controller you should be able to attempt to create a user via websocket, and handle the error that is returned if you attempt to use a non-unique username.

Upvotes: 2

Related Questions