Adding Firebase data, dots and forward slashes

后端 未结 9 2065
长情又很酷
长情又很酷 2020-12-01 12:32

I try to use firebase db, I found very important restrictions, which are not described in firebase help or FAQ.

First problem is that symbol: dot \'.\' prohibited in

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 13:19

    The reason that adding a child 02/10/2013 creates a structure in Firebase is because the forward slashes are resulting in the creation of a new level.

    So the line I assume you are using something similar to: firebaseRef.child('02/10/2013').set(true) is equivalent to firebaseRef.child('02').child('10').child('2013').set(true).

    To avoid the problems of not being able to use the following characters in reference key names (source),

    • . (period)
    • $ (dollar sign)
    • [ (left square bracket)
    • ] (right square bracket)
    • # (hash or pound sign)
    • / (forward slash)

    we can use one of JavaScript's built in encoding functions since as far as I can tell, Firebase does not provide a built in method to do so. Here's a run-through to see which is the most effective for our purposes:

    var forbiddenChars = '.$[]#/'; //contains the forbidden characters
    escape(forbiddenChars); //results in ".%24%5B%5D%23/"
    encodeURI(forbiddenChars); //results in ".%24%5B%5D%23%2F"
    encodeURIComponent(forbiddenChars); //results in ".%24%5B%5D%23%2F"
    

    Evidently, the most effective solution is encodeURIComponent. However, it doesn't solve all our problems. The . character still poses a problem as shown by the above test and trying to encodeURIComponent your test e-mail address. My suggestion would be to chain a replace function after the encodeURIComponent to deal with the periods.

    Here's what the solution would look like for your two example cases:

    encodeURIComponent('Henry.Morgan@caribbean.sea').replace(/\./g, '%2E') //results in "Henry%2EMorgan%40caribbean%2Esea"
    encodeURIComponent('02/10/2013'); //results in "02%2F10%2F2013"
    

    Since both the final results are safe for insertion into a Firebase as a key name, the only other concern is decoding after reading from a Firebase which can be solved with replace('%2E', '.') and a simple decodeURIComponent(...).

提交回复
热议问题