Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Firebase data, dots and forward slashes

Tags:

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 keys,

i.e. firebase reject (with unknown reason) next:

        nameRef.child('[email protected]').set('Pirat'); 

Second problem with forward slashes in your keys '/', when you try to add key like this

        {'02/10/2013': true} 

In firebase you can see:

         '02': {              '10': {                  '2013': true              }          }        

Have you got any ideas how to solve it (automatically)? May be set some flag that it is string key with all symbols? Of course, I can parse/restore data every time before write and after read, but...

By the way '.' '/' - all restricted symbols for firebase ?

like image 522
IL55 Avatar asked Oct 02 '13 08:10

IL55


1 Answers

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('[email protected]').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(...).

like image 179
sushain97 Avatar answered Sep 19 '22 13:09

sushain97