要在Firestore规则中比较文档的时间戳,可以使用Firestore提供的request.time
和request.resource.data
属性来访问文档的创建时间和更新时间。
以下是一个使用Firestore规则比较文档时间戳的示例:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /collection/{documentId} {
allow read: if true; // 允许读取
allow write: if request.auth != null && isBeforeTimestamp(request.resource.data.timestamp); // 允许写入,但只能在指定时间之前
// 自定义函数检查时间戳是否在指定时间之前
function isBeforeTimestamp(timestamp) {
// 获取当前时间
let currentTime = request.time;
// 在规则中,时间戳可以是字符串或时间戳对象
let documentTimestamp = timestamp;
if (typeof timestamp === 'object') {
documentTimestamp = timestamp.toMillis();
} else if (typeof timestamp === 'string') {
documentTimestamp = timestamp.toMillis();
}
// 比较当前时间和文档时间戳
return currentTime < documentTimestamp;
}
}
}
}
在上面的示例中,我们首先定义了一个自定义函数isBeforeTimestamp
,用于检查文档的时间戳是否在指定时间之前。然后,在写入规则中,我们使用isBeforeTimestamp
函数来比较文档的时间戳和当前时间。
请注意,在规则中,时间戳可以是字符串或时间戳对象。因此,我们首先需要将时间戳转换为毫秒数,以便进行比较。
使用上述规则,只有在当前时间早于文档时间戳时才允许写入操作。否则,将拒绝写入请求。