I am writing a lifecycle method on a model that checks to see if a user exists before saving the new record. If the user does not exist, I want the server to respond with a 400 Bad Request code. By default, sails.js seeems always to send back 500. How can I get it to send the code that I want?
Here is my current attempt:
beforeCreate: function(comment, next) {
utils.userExists(comment.user).then(function(userExists) {
if (userExists === false) {
var err = new Error('Failed to locate the user when creating a new comment.');
err.status = 400; // Bad Request
return next(err);
}
return next();
});
},
This code, however, does not work. The server always sends 500 when the user does not exist. Any ideas?
you don't want to do that in a lifecycle callback. Instead, when you're going to make the update, you can do a check of the model and you have access to the res object...for example:
User.find({name: theName}).exec(function(err, foundUser) {
if (err) return res.negotiate(err);
if (!foundUser) {
return res.badRequest('Failed to locate the user when creating a new comment.');
}
// respond with the success
});
This might also be moved into a policy.