tl;dr I’m trying to create a short_id for our users, and check its uniqueness within the following rule. The code below works for one iteration. The problem is as soon as I try to add some looping to the uniqueness check portion, I get a Blocked event loop
error. I’m pretty new to Javascript, but I suspect this is some sort of callback problem?
function (user, context, callback) {
var id_not_unique = true;
function hex(n) {
n = n || 6;
var result = '';
while (n--){
result += Math.floor(Math.random()*16).toString(16).toUpperCase();
}
return result;
}
var ManagementClient = require('auth0@2.9.1').ManagementClient;
var management = new ManagementClient({
token: auth0.accessToken,
domain: auth0.domain
});
// LOOP WOULD START HERE
var short_id = `nurse-${hex(6)}`;
var params = {
search_engine: 'v3',
q: `user_metadata.short_id:"${short_id}"`
};
management.getUsers(params, function (err, matched_user) {
if (Object.keys(matched_user).length === 0) {
id_not_unique = false;
user.user_metadata = user.user_metadata || {};
user.user_metadata.short_id = user.user_metadata.short_id || short_id;
context.idToken['https://mydomain.com/short_id'] = user.user_metadata.short_id;
auth0.users.updateUserMetadata(user.user_id, user.user_metadata)
.then(function(){
callback(null, user, context);
})
.catch(function(err){
callback(err);
});
}
}); // LOOP WOULD END HERE
}