Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularFire2 - check if object exists before update

Let's say I'm collecting a username, and I want to check if this username already exists in my Firebase database. AngularFire2 update or set methods don't actually check if the object exists, but replaces it if so. Is there a way to check that and say return a observable error?

Currently my solution is to retrieve the object and if there are results, I know it exists. I'm looking for a more straightforward way to check that.

I need to do that as a database object, not an actual user in Authentication.

let userExists = false;

this.af.database.object('/users/' + newUser.name).subscribe( user => {
    if (user) {
      userExists = true;
      console.log('This username is taken. Try another one');
    }
    else {
      this._af.database.object('/users/' + newUser.name).update({
         email: '[email protected]',
         password: '!@#$1234'
     })
   }
});
like image 926
Marcos Silva Avatar asked Dec 19 '22 10:12

Marcos Silva


1 Answers

Firebase Transaction

Firebase provides a transaction method for this situation.

transaction() is used to modify the existing value to a new value, ensuring there are no conflicts with other clients writing to the same location at the same time.

If if the value is not present, then you just return the value you previously sent via update.

this.af.database.object('/users/' + newUser.name).$ref.transaction(currentValue => {
  if (currentValue === null) {
    return {email: '[email protected]', password: '!@#$1234'};
  } else {
    console.log('This username is taken. Try another one');
    return Promise.reject(Error('username is taken'))
  }
})
.then( result => {
   // Good to go, user does not exist
   if (result.committed) {
      // TODO: Take additional action
   }
})
.catch( error => {
   // handle error
});

It's important to note that this is a method from the Firebase API (not Angularfire2), but you can still access those methods by calling $ref.

like image 154
adriancarriger Avatar answered Dec 28 '22 14:12

adriancarriger