I'm trying to use a module to handle my user sign up and login process. What I'd like to do is have a module with, for example, a "register" endpoint but rather than putting all the code in the one function, I'd split it into separate parts like validUsername, validPassword etc to check if the given values are acceptable.
The trouble I have is that whenever this route is run, I get this error:
TypeError: Object #<Object> has no method 'validUsername'
server.js
var user = require('./routes/user.js')(mongoose, bcrypt);
express.post('/user', user.create);
user.js
module.exports = function(mongoose, bcrypt){
return {
validUsername: function(username){
// Ensure a username is present
if(username == null){
return false;
}
// Ensure it is at least 2 characters
if(username.length <= 2){
return false;
}
return true;
},
validPassword: function(password){
// Ensure a password is present
if(password == null){
return false;
}
// Ensure it is at least 9 characters
if(password.length < 9){
return false;
}
return true;
},
create: function(req, res){
// Extract the new user data from the post body
var username = req.body.username || null;
var password = req.body.password || null;
// Ensure the details are acceptable
if(!this.validUsername(username))
{
res.send(400,{'field':'username','error':'invalid'});
}
else if(!this.validPassword(password))
{
res.send(400,{'field':'password','error':'invalid'});
}
else
{
// ... Create new user etc ...
}
}
};
};
I'm assuming the reason for the error is because when setting up the route, only the 'create' function is passed in and therefore it is unable to "see" the rest of the functions in the same module.
So how can I solve this issue and have the create function still access those validation functions when used as a route endpoint?
The fix is to either use .bind()
:
express.post('/user', user.create.bind(user));
or to use a wrapper:
express.post('/user', function(req, res) { user.create(req, res); });