You can use the cast_as_int
function defined below:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function cast_as_int(x) {
let pattern = '[+-]?([0-9]*[.])?[0-9]+';
return (
(x is float)
|| (x is int)
|| (x is string) && (x.matches(pattern))
) ? int(float(x)) : null;
}
// All gets will succeed
match /{document=**} {
allow get: if cast_as_int(1) == 1
&& cast_as_int('2') == 2
&& cast_as_int('3.14') == 3
&& cast_as_int(4.44) == 4
&& cast_as_int("5!") != 5;
}
}
}
The function takes in an variable and returns either an Integer or null.
Firestore does not allow statements to evaluate to multiple types, so the function can only return Integer
or null
(not false
as requested).
The function assumes you want to convert from (Integer or Float) to Integer. If you only want to convert from Integer to Integer, then replace int(float(x))
with int(x)
.
The regex for let pattern = '[+-]?([0-9]*[.])?[0-9]+'
was taken this StackOverflow Question