In firebase, how can I detect what value is existing?

94 views Asked by At

What I want to create is just a 'room-maker' app.

This is just an app that if user input a room Number and click the "Join" button,

new room is created and the user go to the room(route).

In Firebase, I want to know how I can detect whether room is already existing or not.

I want to make a code like below.

if room is exist,

console.log("The room is existing.");

if not,

console.log("You created new room!");

My code(partial) is below

    //Firebase Set
    var ref = new Firebase('https://blinding-inferno-7068.firebaseio.com/');

    //Room set
    $scope.roomNum = $stateParams.roomNum;
    var roomsRef = ref.child('rooms');
    var roomNumRef = roomsRef.child($scope.roomNum);
    roomNumRef.set({roomNum:$scope.roomNum});

I completed the code that make a new room, but how can I detect a room is already existing or not?

1

There are 1 answers

1
Frank van Puffelen On BEST ANSWER

If I understand your core requirement it's: if the room doesn't exists yet, the current user creates it and nobody else can create that room anymore.

That reads like a transaction to me.

roomNumRef.transaction(function(current) {
  if (!current) {
    console.log('You created the room');
    return {
      creator: 'nujabes',
      createdAt: Firebase.ServerValue.TIMESTAMP
    }
  }
  else {
    console.log('The room already existed');
  }
});

The transaction handler gets called with the current value of the room node. If you return a value from the handler, that value will be set at the room node. If you return nothing, the room node will be left unmodified.

Since Firebase will prune empty nodes, we must return some value. In this case, I set creator to a hard-coded value. But you'll probably want to identify the actual user.

Note that the above prevents that two users create the same room only if they're both using this code. A malicious user can easily run their own code against your Firebase database and still claim any room in there. To prevent this, you'll need to set up security rules that prevent this. Read this documentation on Firebase security rules to learn how to do that.