mercredi 11 avril 2018

How to handle TypeScript promises with conditional branches?

I am accessing a firebase database and I would like to do the following. When a user logs in, I need to check the state of a variable in the database. Depending on the state of this variable, I then want to do one of two things. My code looks like this, but isn't correct.

firebase.database( ).ref( `sessions/${user.uid}` ).once( 'value' )
  .then( ( data : firebase.database.DataSnapshot ) => {
    if( !data.exists( ) ) {
      console.log( 'No active sessions. Creating a new one' );
      const sessionKey = firebase.database( ).ref( `sessions/${user.uid}` ).push( ).key;
      return firebase.database( ).ref( `sessions/${user.uid}/${sessionKey}` ).update( {
        myStruct: {
          myValue: 123,
        }
      } );
    } else {
      console.log( 'Found an existing session' );
      const obj = data.val( );
      const sessionKey = Object.keys( obj )[0];
      return firebase.database( ).ref( `sessions/${user.uid}/${sessionKey}` ).once( 'value' );
    }
  } )
  .then( ( data : any ) => {
    //what is data here?  Is it coming from the .update call, or from the .once call ??
    //if this is coming from the update call then I want to perform some stuff,
    //however if it is coming from the .once call, then I want to retrieve the myStruct.myValue and perform some other stuff.
  } )
  .catch( ( error : firebase.auth.Error ) => {
    console.log( error );
  } );

Aucun commentaire:

Enregistrer un commentaire