google-cloud-firestore - Firestore Security rules - checking if a string can be cast to an int
问题描述
There is this page showing how to convert a string to an int:
int("2") == 2
int(2.0) == 2
But how can I know before doing the conversion whether it will work or throw an exception?
For instance how can I implement the following:
IF x can be cast to an integer THEN return int(x) < 10
ELSE IF y can be cast to an integer THEN return int(y) < 10
ELSE return false
解决方案
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
推荐阅读
- python - Opencv readNetFromTensorflow 因未知枚举 DT_VARIANT 而失败
- java - 创建集成测试
- django - 如何从 django 中的数据库查询中获取不同的记录?
- python - 为什么类型列表的元素访问比使用 Numba 的数组慢得多?
- reactjs - MUI DataGrid 替换分页 - validateDOMNesting(...):不能作为子级出现
- excel - VBA 代码问题:在循环遍历特定值的范围时使用偏移量
- php - Laravel 缓存助手“驱动程序”未实现
- ios - 从 blob url 下载 WKWebview 文件
- json - Nuxt 正在返回 html 而不是我从 api 获得的 JSON
- javascript - 如何处理具有角度浏览器支持的窗口卸载事件?