我正在尝试使用onWrite
fordb_uppercaseLog
但它不会触发。当我使用时onCreate
,它确实会触发。
db_uppercaseLog
侦听添加到的新日志/log/:pushId/original
并创建日志的大写版本/log/:pushId/uppercase
onCreate((snapshot,context)=>{...} // works fine
onWrite((snapshot,context)=>{...} // did not work
我已经阅读了文档和参考资料。在stackoverflow上也读过类似的问题。但我无法与我的案子联系起来。这应该是教科书的例子吧?
我在这里做错了什么?
// Take the text parameter passed to this HTTP endpoint and insert it into the
// Realtime Database under the path /log/:pushId/original
// <host>/pushLog?text=
exports.pushLog=functions.https
.onRequest(async(req,res)=>{
// Grab the text parameter.
const original = req.query.text;
// Push the new log into the Realtime Database using the Firebase Admin SDK.
const snapshot = await admin.database().ref('/log').push({original: original});
res.status(200).send(
`<!doctype html><head><title>pushLog</title></head><body>
<a href="${snapshot.ref.toString()}" target="_blank">${original} was saved</a>
</body></html>`
);
});
// Listens for new log added to /log/:pushId/original and creates an
// uppercase version of the log to /log/:pushId/uppercase
exports.db_uppercaseLog=functions.database
.ref('/log/{pushId}/original')
.onWrite((snapshot,context)=>{
// Grab the current value of what was written to the Realtime Database.
const original = snapshot.val();
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);
});
您的问题源于此onWrite
,以onCreate
不同的方式处理数据,并且定义与您的问题不同。
onCreate((snapshot,context)=>{...})
onWrite((change,context)=>{...})
特别是,一个Change 对象是一个容器,它包含属性after
和before
,代表触发函数的状态变化。
与onWrite
更改处理程序一样 - 如果不进行审核,它可以重新触发自身进入无限循环。在上面的代码中,这不是问题,但需要注意。但是当值被删除时你的代码会被触发,所以决定你希望如何处理它。
// Listens for changes at /log/:pushId/original and creates an
// uppercase version of the log at /log/:pushId/uppercase
exports.db_uppercaseLog=functions.database
.ref('/log/{pushId}/original')
.onWrite((change,context)=>{
let afterSnapshot = change.after;
// onWrite is triggered on deletion
if (!afterSnapshot.exists()) {
console.log('cancelled: entry deleted');
return; // do nothing (could also delete /log/:pushId/uppercase?)
}
// Grab the new value written to the Realtime Database and modify it.
const newValue = afterSnapshot.val();
const uppercase = newValue.toUpperCase();
// Set "../uppercase" and returns its operation Promise.
return afterSnapshot.ref.parent.child('uppercase').set(uppercase);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句