Home > database >  How to parse key as a number in a Firebase Realtime Database rule?
How to parse key as a number in a Firebase Realtime Database rule?

Time:08-14

I am using an unix epoch timestamp as a key (to prevent double push for particular second and sort by push date), and i d like to prevent user to push beyond the current timestamp.

"$timestamp": {
 ".write": "now/1000 - $timestamp > 0"
}

database: database.rules.json:XX:XX: Invalid - expression: right operand is not a number.`

As stated in the documentation, key are always strings, and numbers cant be compared to key (well, the doc pretend otherwise with a strange concatenation example..?).

Is there any way to parse key into a number inside a Realtime Database rule so i may use it with every comparison operators?

NOTE: Here is my current workaround which imply redundant data:

"$timestamp": {
 ".write": "now/1000 - newData.child('typed_timestamp').val() > 0",
 "body":{},
 "typed_timestamp": {
".validate": "newData.isNumber() && newData.val() '' == $timestamp"
}
}

CodePudding user response:

The documentation is showing an example of string concatenation where the left side of the expression is a string, using the operator to append a number $room_id on the right to it:

".validate": "root.child('room_names/'   $room_id).exists()"

It's important to note that the string on the left ensures that string concatenation will take place rather than numeric math.

You can do the same thing to create a string from a number using an empty string on the left and a number on the right:

''   (now/1000)

As a side note, I will say that using numbers for keys is not a good idea in Realtime Database. When using numbers as keys, it's possible that RTDB will interpret them as array indexes, which means your queries will end up producing arrays instead of maps. That's one reason why the database prefers to use string push IDs. (Also, the push ID is far more likely to be truly unique.) It's preferred to use a timestamp number value as a child, then use that child value in your rules for limiting writes based on timestamp.

  • Related