Reputation: 1776
I'm working on my first Node.js-project and I've stumbled over a problem. I'm using node-validator for input validation and Sequelize as an ORM.
I'm trying to write some custom validation to see if a given username is still available. Only problem is: finders in Sequelize are asynchronous while node-validator has no built-in support for asynchronous validation.
I'm satisfied with neither approach mentioned above. Using callbacks gets messy very quickly and there are other problems if I use Sequelize's built-in validation.
Apparently, there is no way to use finders synchronously in Sequelize, which would have been my go-to-solution.
What options do I have to solve this problem in a clean fashion? Ideally, I'd like my validation-process to look something like this:
req.sanitize('username').trim();
req.check('username', 'Your username must be between 4 and 32 characters long').len(4, 32);
req.check('username', 'That username is already taken').usernameIsAvailable();
How can I implement asynchronous validation cleanly? Thank you for your help!
Upvotes: 2
Views: 1692
Reputation: 34337
You definitely are not going to find a synchronous solution. Node is synonymous with asynchronous.
The way most of us deal with callback spaghetti is to use the async library, which is used by 1000 npm modules. https://github.com/caolan/async#series will let you put those three functions in order, as if they were running synchronously.
However, the most idiomatic way of dealing with the issue would be to specify the username requirements in your Sequelize model (which already includes node-validator), and then write the code to report Sequelize errors back to the user, when a username already exists or is invalid. That is, Sequelize already gives you asynchronous access to all node-validator functions, so I can't really see why you would want to pre-check anything.
Upvotes: 1