2016-06-14 50 views
0

我增加了一個輔助函數來獲取/設置值如下:老FB延長firebase.database.Reference

// val() -> get(), resolve with value at ref 
    // val(value) -> set(value), resolve with value 
    // val(vals) -> update(vals), resolve with vals 
    Firebase.prototype.val = function(vals) { 
     let self=this; 

     if (!vals) { 
      return this.once('value').then(
       snapshot => { 
        if (typeof snapshot.val() === 'undefined' || snapshot.val() === null) throw 'INVALID_VALUE'; 
        return snapshot.val(); 
       }, 
       err => { 
        throw err; 
       }); 
     } 

     let singleVal=(vals.constructor != Object); // is singleVal then vals is a single value 

     if (singleVal) return this.set(vals); // set single value 

     if (!singleVal) return this.update(vals).then(() => vals); // update multiple values 
    }; 
} 

我可以再例如收益ref.child(...)做VAL ();

該功能不能在V3中運行。

如何在V3中以這種方式擴展Firebase?

thx!

回答

0

這裏的解決方案 - 我覺得這個擴展非常方便

// val() -> get(), resolve with value at ref, fails with error.code 
    // val(value) -> set(value), resolve with value, fails with error.code 
    // val(vals) -> update(vals), resolve with vals, fails with error.code 

    firebase.database.Reference.prototype.val = function(vals) { 
     let path=this.toString().substring(firebase.database().ref().toString().length-1); 
     let valsAsString = (typeof vals==='string' ? vals : JSON.stringify(vals)); 

     if (!vals) { 
      return this.once('value').then(
       snapshot => { 
        if (typeof snapshot.val() === 'undefined' || snapshot.val() === null) { 
         console.log('val('+path+') failed (null) ! '+error.message+' ('+error.code+')'); 
         throw 'INVALID_VALUE'; 
        } 
        return snapshot.val(); }, 
       error => { 
        console.log('val('+path+') failed ! '+error.message+' ('+error.code+')'); 
        throw error.code; 
       }); 
     } 

     let singleVal=(vals.constructor != Object); // is singleVal then vals is a single value 

     if (singleVal) return this.set(vals).then( // set single value 
      () => { 
       return vals; 
      }, error => { 
       console.log('val('+path+','+valsAsString+') failed ! '+error.message+' ('+error.code+')'); 
       throw error.code; 
      } 
     ); 

     return this.update(vals).then(// update multiple values 
      () => { 
       return vals; 
      }, error => { 
       console.log('val('+path+','+valsAsString+') failed ! '+error.message+' ('+error.code+')'); 
       throw error.code; 
      } 
     ); 
    }; 
}