【发布时间】:2018-11-29 00:40:48
【问题描述】:
当在 firebase 上使用云函数时,通过 onUpdate 触发器,我如何检索已更新的记录(换句话说,触发函数的记录)?我正在使用 JavaScript 与 Firebase 数据库交互。
【问题讨论】:
标签: javascript firebase firebase-realtime-database google-cloud-functions
当在 firebase 上使用云函数时,通过 onUpdate 触发器,我如何检索已更新的记录(换句话说,触发函数的记录)?我正在使用 JavaScript 与 Firebase 数据库交互。
【问题讨论】:
标签: javascript firebase firebase-realtime-database google-cloud-functions
传递给onUpdate 处理函数的第一个参数是Change 对象。这个对象有两个属性,before 和after,都是DataSnapshot 对象。这些 DataSnapshot 对象描述了触发函数的更改前后的数据库内容。
exports.foo = functions.database.ref('/location-of-interest')
.onUpdate((change) => {
const before = change.before // DataSnapshot before the change
const after = change.after // DataSnapshot after the change
})
【讨论】:
每https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder#onUpdate
onUpdate(handler) => function(functions.Change containing non-null functions.database.DataSnapshot, optional non-null functions.EventContext)
所以我猜你只需要将回调函数传递给onUpdate(callback) 触发器。根据文档,已更新的记录似乎作为第一个参数传入。我将从在回调函数中记录参数对象开始。
文档里面的例子是:
// Listens for new messages added to /messages/:pushId/original and creates an
// uppercase version of the message to /messages/:pushId/uppercase
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
.onCreate((snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
const original = snapshot.val();
console.log('Uppercasing', context.params.pushId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing asynchronous tasks inside a Functions such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the Realtime Database returns a Promise.
return snapshot.ref.parent.child('uppercase').set(uppercase);
});
【讨论】: