我只是在尝试Firebase的云函数,以便将我的firebase-queue工作人员转移到云函数上。我添加了一个简单的函数,每当我在给定的ref上创建一个新节点时,都会添加一个上次更新的时间戳。该函数如下所示:
var functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.setLastUpdatedTimestamp = functions.database.ref('/nodes/{nodeId}')
.onWrite(event => {
const original = event.data.val();
console.log('Adding lastUpdatedTimestamp to node ', original.name);
return event.data.ref.child('lastUpdatedAtFromFC').set(Date.now());
});我部署了这个云函数,并从我的应用程序中仅添加了一个节点。我转到Firebase Functions仪表板,看到该函数已被调用169次,但我不知道为什么。当我查看日志时,我看到了类似于将函数附加到所有过去节点的日志。
情况是这样的吗?onWrite的行为类似于child_added,并为所有现有实体运行该函数吗?
当我再次更改和部署函数时,此操作是否会重复?
我希望它对新添加的节点只运行一次。
发布于 2017-03-17 00:08:47
在编写处理数据库写入的函数时,这是一个常见的错误。当您在某个位置处理初始写操作的事件,然后对同一位置进行第二次写回时,第二次写操作将触发另一个事件,该事件将再次运行函数,依此类推,这将是一个无限循环。
您的函数中需要一些逻辑来确定第二个写入事件是否应该重写到数据库。这将停止循环。在您的例子中,您不需要一个函数来设置上次更新时间。您可以在客户端使用一个特殊的值来执行此操作,以告知服务器将当前时间插入字段中。
https://firebase.google.com/docs/reference/js/firebase.database.ServerValue#.TIMESTAMP
发布于 2017-03-17 01:54:12
道格是对的。此外,最好知道如果有一个函数陷入无限循环,停止它的方法是重新部署您的函数(使用firebase deploy)并修复该循环,或者完全删除该函数(通过从index.js中删除它并运行firebase deploy)。
发布于 2018-06-24 19:45:05
我就遇到了这个问题。这里有两个问题。如何在无限循环开始后停止它。这个问题已经得到了回答。但真正的问题是如何使用Firebase Cloud Function触发器将lastUpdated日期字段添加到对象中。
这是我处理onWrite()循环问题的尝试。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.onWriteFeatherUpdateSummary = functions.database.ref('/messages/{id}')
.onWrite((change, context) => {
// Grab the current value of what was written to the Realtime Database.
let updated = change.after.val();
// Grab the previous value of what was written to the Realtime Database.
const previous = change.before.val();
let isChanged = true;
let isCreated = (previous === null); // object 'created'
// Only when the object gets updated
if (!isCreated) {
// An object should never directly change the lastUpdated value, this is for trhe trigger only
isChanged = (updated.lastUpdated === previous.lastUpdated);
}
console.log(`isChanged: ${isChanged} ; isCreated: ${isCreated}`);
if(isChanged) {
// Insert whatever extra data you wnat on the update trigger
const summary = `This is an update!`;
// Add a 'createdDate' field on the first trigger
if (isCreated) {
// Make sure your object has a createdDate (Date) before the lastUpdated (Date)!
Object.assign(updated,
{
createdDate : admin.database.ServerValue.TIMESTAMP
}
);
}
// Add lastUpdated Date field on very update trigger (but not when you just changed it with the trigger!)
Object.assign(updated,
{
summary : summary,
lastUpdated : admin.database.ServerValue.TIMESTAMP
}
);
}
return change.after.ref.set(updated);
});https://stackoverflow.com/questions/42835339
复制相似问题