firestore规则路径的大小

时间:2018-03-09 11:56:04

标签: firebase google-cloud-firestore

我正在尝试使用firestore规则中路径的大小,但无法获得任何工作,并且无法在firestore文档中找到有关如何执行此操作的任何引用。

我想将最后一个集合名称用作规则中的参数,因此尝试了这个:

match test/{document=**}
   allow read, write: if document[document.size() - 2] == 'subpath';

但是.size()似乎不起作用,也没有.length

2 个答案:

答案 0 :(得分:0)

您可以学习规则here

   // Allow reads of documents that begin with 'abcdef'
   match /{document} {
      allow read: if document[0:6] == 'abcdef';
   }

答案 1 :(得分:0)

可以这样做,但是您首先必须强制转换为字符串的路径。

要获取当前资源的路径,可以使用__name__属性。

https://firebase.google.com/docs/reference/rules/rules.firestore.Resource#name

作为参考,resource是一个常规属性,可用于表示正在读取或写入的Firestore文档的每个请求。

https://firebase.google.com/docs/reference/rules/rules.firestore.Resource

resource['__name__']

__name__返回的值是Path,缺少有用的方法,因此在使用size之前,您需要将Path强制转换为字符串。

https://firebase.google.com/docs/reference/rules/rules.String.html

string(resource['__name__'])

一旦转换为字符串,则可以在split运算符上/将该字符串转换为List的字符串路径部分。

https://firebase.google.com/docs/reference/rules/rules.String.html#split

string(resource['__name__']).split('/')

现在,您可以使用列表的size方法检索列表的大小。

https://firebase.google.com/docs/reference/rules/rules.List#size

string(resource['__name__']).split('/').size()

关于Firestore规则的一项具有挑战性的事情是,不支持变量,因此,当您需要多次使用结果时,通常会重复执行代码。例如,在这种情况下,我们需要使用分割结果两次,但不能将其存储到变量中。

string(resource['__name__']).split('/')[string(resource['__name__']).split('/').size() - 2]

您可以通过使用函数并将参数用作变量来对此进行干燥。

function getSecondToLastPathPart(pathParts) {
  return pathParts[pathParts.size() - 2];
}

getSecondToLastPathPart(string(resource['__name__']).split('/'))

将它们结合在一起以解决问题,看起来像这样...

function getSecondToLastPathPart(pathParts) {
  return pathParts[pathParts.size() - 2];
}

match test/{document=**} {
   allow read, write: if getSecondToLastPathPart(string(resource['__name__']).split('/')) == 'subpath';
}

希望这会有所帮助!

相关问题