Firestore的onDelete触发函数中能否获取事件发生时间戳?
获取Firestore删除触发器事件实际发生时间的方法
不管是onDelete()触发,还是onWrite()触发后检测到change.after.exists === false的场景,都不需要依赖change.after对象的字段,直接从事件本身的元数据里就能拿到数据库操作的准确发生时间,不需要用存在延迟误差的Timestamp.now()。
v1版Cloud Functions实现
v1版本的触发器回调第二个参数是上下文对象,事件时间存在context.timestamp字段里,这个值是Firestore服务端记录的操作提交时间,和函数冷启动、调度排队带来的执行延迟无关,和你之前在写入场景用的change.after.updateTime精度、语义完全一致:
exports.handleDocDelete = functions.firestore .document('your_collection/{doc_id}') .onDelete((snap, context) => { // 拿到删除操作实际发生的服务端时间字符串 const rawEventTime = context.timestamp // 需要转成Firestore Timestamp类型可以直接转换 const eventTs = admin.firestore.Timestamp.fromDate(new Date(rawEventTime)) // 后续业务逻辑 })
如果是onWrite()场景,不管是写入还是删除,都可以直接取这个字段,不需要判断文档是否存在:
exports.handleDocWrite = functions.firestore .document('your_collection/{doc_id}') .onWrite((change, context) => { // 不管create/update/delete,这个字段都是操作实际发生时间 const eventTime = context.timestamp })
v2版Cloud Functions实现
v2版本的触发器把事件元数据直接挂在回调的第一个事件对象上,时间字段是event.eventTime,不需要传上下文参数:
const { onDocumentDeleted, onDocumentWritten } = require("firebase-functions/v2/firestore"); exports.handleDocDeleteV2 = onDocumentDeleted("your_collection/{doc_id}", (event) => { const eventTime = event.eventTime // 删除操作的实际发生时间 })
补充说明:你之前在
onCreate/onUpdate场景拿到的change.after.updateTime,本质和上面提到的事件元数据里的时间是同一个值,都是服务端在操作提交时生成的时间戳。删除场景因为文档已经不存在,change.after是一个空的文档快照,自然没有updateTime字段,直接取事件元数据的时间即可。
内容的提问来源于stack exchange,提问作者matth
相关产品推荐
相关产品推荐

