I am generating a token using “hat”.
I am trying to write very paranoid code. So, the idea is that the system generates an ID, checks if it’s already taken (querying the DB), and if it hasn’t, it returns it. If it has, tries again, 5 times. After 5 times, something very strange is going on and the application throws an error.
The short question is: how can I make this code run 5 times, in sequence, with the option of calling the passed callback (see, “quit” the cycle) if the token is actually available?
Is is the code that only attempts once:
var hat = require('hat'),
mongoose = require('mongoose');
exports.makeToken = function( callback ){
Workspace = mongoose.model("Workspace");
var found = false;
var token;
// Generate the token, check that it's indeed available
token = hat();
Workspace.findOne( { 'access.token':token } , function(err, doc){
if(err){
callback(err, null);
} else {
if( doc ){
callback( new Error("Cannot generate unique token"), null );
} else {
callback(null, token );
}
}
});
}
Unfortunately, I cannot use the ObjectId because 1) The user might decide to regenerate the token key 2) Users are not stored as individual documents.
So, there is a chance that the token generated is not unique, which would give me a situation where there is the same token ID for two user<->workspace pair, which wouldn’t be good. Hence, the 5 attempts. I ADMIT that chances are pretty slim, but still…
I came up with this (recursion is needed here):