Skip to content

Instantly share code, notes, and snippets.

@guibot17
Forked from anantn/firebase_create.js
Last active September 15, 2015 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guibot17/d1d59c34af65ad97deba to your computer and use it in GitHub Desktop.
Save guibot17/d1d59c34af65ad97deba to your computer and use it in GitHub Desktop.
Firebase: Creating data if it doesn't exist. This snippet creates a user only if it doesn't already exist.
function go() {
var userId = prompt('Username?', 'Guest');
var userData = { name: userId };
tryCreateUser(userId, userData);
}
var USERS_LOCATION = 'https://SampleChat.firebaseIO-demo.com/users';
function userCreated(userId, success) {
if (!success) {
alert('user ' + userId + ' already exists!');
} else {
alert('Successfully created ' + userId);
}
}
// Tries to set /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