You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Firebase Rules中验证UUID格式的节点键?

问题描述

我的Realtime Firebase数据库数据结构如下:

{
  "comments": {
    "${project_uuid}": {
      "${thread_uuid}": {
        "author": 12,
        "data": "who lot of text"
      }
    }
  }
}

我需要确保comments节点下的所有子节点键都是UUID格式,于是用Bolt编写Firebase规则,但遇到了问题——key()函数无法按预期工作:

path /comments {
   read() { auth != null }
   write() { auth != null }

   /{project_uuid} is UuidOnly {
       /{thread_uuid} is Thread;
   }      
}

type Thread {
   author: Number,
   data: String,
}

type UuidOnly {
  validate() {
    // 这行代码有问题,key()无法正常使用
    this.parent().key().test(/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$/)
  }
}

请问该如何修改规则,实现comments下仅存在UUID格式子节点的验证?


解决方案

问题出在你对Bolt中key()方法的使用上,正确的做法是直接获取当前节点的键来验证,而不是父节点的。有两种可行的修改方式:

方式一:直接引用路径变量

在UuidOnly的验证逻辑中,直接用定义的路径变量$project_uuid来验证键的格式:

path /comments {
   read() { auth != null }
   write() { auth != null }

   /{project_uuid} is UuidOnly {
       // 如果thread_uuid也需要UUID验证,同样加上is UuidOnly约束
       /{thread_uuid} is UuidOnly;
       /{thread_uuid} is Thread;
   }      
}

type Thread {
   author: Number,
   data: String,
}

type UuidOnly {
  validate() {
    $project_uuid.test(/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$/)
  }
}

方式二:通用写法(推荐)

使用this.key()获取当前节点的键,这样这个类型可以复用在任何需要验证UUID键的节点上,不用依赖具体的路径变量名:

path /comments {
   read() { auth != null }
   write() { auth != null }

   /{project_uuid} is UuidOnly {
       /{thread_uuid} is UuidOnly;
       /{thread_uuid} is Thread;
   }      
}

type Thread {
   author: Number,
   data: String,
}

type UuidOnly {
  validate() {
    this.key().test(/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$/)
  }
}

关键说明

  • 你之前用this.parent().key()会获取到父节点(也就是comments)的键,这显然不是你要验证的目标,所以验证失败。
  • 如果thread_uuid也需要是UUID格式,直接给/{thread_uuid}加上is UuidOnly约束即可,复用同一个类型,避免重复代码。

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 11:55:19