I need to do one method linkedIn like that generates automatically a username after registering.
To do so i followed this logic:
1 - get the name and surname and make a join (if name is Tom and surname Hanks then base username would be tomhanks)
2 - I check if that username already exists in the database.
2.1 if it doesn't exist then I return it
2.2 if it exists then I add a suffix and recall the function with the parameter base username + suffix
That's it.
I did the following code:
export const buildUsername = async (value) => {
const { db } = await connectToDatabase(URI, DATABASE);
let obj = await db.collection(COLLECTION).findOne({username: value});
if(obj != null) {
suffix +=1;
buildUsername(value + suffix)
}else{
suffix = 1;
return value;
}
}
In the post method I did the following:
let username = buildUsername(user.name + user.surname)
//I pretend username to contain a unique username so i could register it into the DB
The problem is that this method doesn't work well. if the username is unique at the first step then it returns it right. If there need to do some recursions then 'username' is undefined. I have to say that if I log the value before returning it, it seems to work and logs the base username with some numbers after..
What do you think? Is it the right method to do it? Or I just have to think differently?
Thank you very much!