Firebase HTTPS云功能触发两次

时间:2017-06-26 06:57:06

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

我已阅读Firebase云端功能referenceguidessample code以尝试确定我的功能被触发两次的原因,但尚未找到成功解决方案。我还尝试了Firebase-Queue作为解决方案,但是它的最新更新表明云功能是最佳选择。

简而言之,我使用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}`);
    });
}

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

1 个答案:

答案 0 :(得分:0)

问题已解决 - 来自Firebase控制台日志的一些错误信息(重复条目),加上错误顺序的嵌套for循环,导致明显的双重触发。