Last active
July 5, 2017 22:06
-
-
Save codenamejason/38f15d437588f5a29277 to your computer and use it in GitHub Desktop.
Create user if does not exist already
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function go() { | |
var userId = prompt('Username?', 'Guest'); | |
var userData = { name: userId }; | |
tryCreateUser(userId, userData); | |
} | |
var USERS_LOCATION = 'https://<Firebase URL>.com/users'; | |
function userCreated(userId, success) { | |
if (!success) { | |
alert('user ' + userId + ' already exists!'); | |
} else { | |
alert('Successfully created ' + userId); | |
} | |
} | |
// Tries to set the users <userId> to the specified data, but only | |
// if there's no data there already. | |
function tryCreateUser(userId, userData) { | |
var usersRef = new Firebase(USERS_LOCATION); | |
usersRef.child(userId).transaction(function(currentUserData) { | |
if (currentUserData === null) | |
return userData; | |
}, function(error, committed) { | |
userCreated(userId, committed); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment