【问题标题】:Firebase HTTPS Cloud Function Triggered TwiceFirebase HTTPS 云函数触发两次
【发布时间】:2017-06-26 06:57:05
【问题描述】:

我已通读 Firebase 云函数 referenceguidessample code,试图确定我的函数被触发两次的原因,但尚未找到成功的解决方案。我还试用了 Firebase-Queue 作为解决方法,但它的最新更新表明 Cloud Functions 是可行的方法。

简而言之,我正在使用 request-promise 从外部 API 检索通知,将这些通知与我的数据库中已有的通知进行检查,当发现新通知时,将其发布到所述数据库。然后参考新通知更新相应的地点。代码如下:

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const request = require('request');
const rp = require('request-promise');

admin.initializeApp(functions.config().firebase);

const db = admin.database();
const venues = db.ref("/venues/");

exports.getNotices = functions.https.onRequest((req, res) => {
    var options = {
        uri: 'https://xxxxx.xxxxx',
        qs: {
            format: 'json',
            type: 'venue',
            ...
        },
        json: true
    };
    rp(options).then(data => {
            processNotices(data);
            console.log(`venues received: ${data.length}`);
            res.status(200).send('OK');
        })
        .catch(error => {
            console.log(`Caught Error: ${error}`);
            res.status(`${error.statusCode}`).send(`Error: ${error.statusCode}`);
    });
});

function processNotices(data) {
    venues.once("value").then(snapshot => {
        snapshot.forEach(childSnapshot => {
            var existingKey = childSnapshot.val().key;
            for (var i = 0; i < data.length; i++) {
                var notice = data[i];
                var noticeKey = notice.key;
                if (noticeKey !== existingKey) {
                    console.log(`New notice identified: ${noticeKey}`)
                    postNotice(notice);
                }
            }
            return true;
        });
    });
}

function postNotice(notice) {
    var ref = venues.push();
    var key = ref.key;
    var loc = notice.location;
    return ref.set(notice).then(() => {
        console.log('notice posted...');
        updateVenue(key, loc);
    });
}

function updateVenue(key, location) {
    var updates = {};
    updates[key] = "true";
    var venueNoticesRef = db.ref("/venues/" + location + "/notices/");
    return venueNoticesRef.update(updates).then(() => {
        console.log(`${location} successfully updated with ${key}`);
    });
}

任何关于如何纠正双重触发的建议将不胜感激。提前致谢!

【问题讨论】:

  • 您如何调用它以使其只执行一次?日志显示什么?
  • 另请注意,您正在执行异步数据库工作,而无需等待它在 processNotices() 中完成。它应该返回一个承诺,以便调用者可以在向客户端发送响应之前知道数据库工作何时完全完成。
  • 感谢您的提示,@DougStevenson。我找到了解决方案(详情如下)。

标签: javascript json firebase firebase-realtime-database request-promise


【解决方案1】:

问题已解决 - Firebase 控制台日志中的一些错误信息(重复条目)以及错误顺序的嵌套 for 循环是造成明显双重触发的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-08
    • 2018-09-14
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2021-10-27
    相关资源
    最近更新 更多