Firebase的Cloud Functions已多次调用 [英] Cloud Functions for Firebase invoked many times

查看:60
本文介绍了Firebase的Cloud Functions已多次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试Firebase的云功能,以将我的firebase-queue工作人员转移到云功能中.每当我在给定的引用处创建新节点时,我都添加了一个简单函数来添加上次更新的时间戳.该函数如下所示:

I am just trying out Cloud Functions for Firebase in an effort to move my firebase-queue workers over to the cloud functions. I added a simple function to add a last updated timestamp whenever I create a new node at a given ref. The function looks like this:

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次,我也不知道为什么.当查看日志时,也会看到类似将功能附加到所有过去节点的日志.

I deployed this cloud function and added just one node from my app. I went to the Firebase Functions dashboard and see that the function has been invoked 169 times and I have no idea why. When I look at the logs, I see logs like attaching the function to all the past nodes as well.

是不是onWrite的行为类似于child_added并为所有现有实体运行该函数?

Is it the case that the onWrite would behave kind of like child_added and run the function for all the existing entities as well?

每次更改并再次部署功能时,都会重复执行此操作吗?

Would this action be repeated every time I change and deploy the function again?

我希望它对于新添加的节点只运行一次.

I was expecting it to run just once for the newly added node.

推荐答案

在编写处理数据库写操作的函数时,这是一个常见错误.当您在某个位置处理初始写入事件时,然后再次写入该位置,则该第二次写入将触发另一个事件,该事件将再次运行该函数,依此类推,这将是一个无限循环.

This is a common mistake when writing functions that deal with database writes. When you handle the event for the initial write at a location, then do a second write back to that same location, that second write will trigger yet another event that will run the function again, and so on, which will be an infinite loop.

您的函数中需要一些逻辑,以确定是否不应将第二个写入事件重新写入数据库.这将停止循环.在您的情况下,您不需要设置最后更新时间的功能.您可以在客户端上使用特殊值来执行此操作,以告诉服务器将当前时间插入字段.

You need some logic in your function that determines if the second write event should not re-write to the database. That will stop the loop. In your case, you don't need a function to set the last update time. You can do that with a special value on the client to tell the server to insert the current time into a field.

https://firebase.google.com/docs /reference/js/firebase.database.ServerValue#.TIMESTAMP

这篇关于Firebase的Cloud Functions已多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆