I have thoroughly reviewed the Firebase Cloud Functions reference, guides, and sample code in an attempt to solve the issue of my function being triggered twice, but so far, I have not found a solution. I also experimented with Firebase-Queue as a workaround, but the latest update indicates that Cloud Functions is the preferred approach.
In summary, I am fetching notices from an external API using request-promise
, comparing them to existing notices in my database, and adding new notices to the database if they are identified as new. Subsequently, the associated venue is updated with a reference to the new notice. Below is the code snippet:
'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}`);
});
}
I would greatly appreciate any suggestions on how to fix the issue of double-triggering. Thank you in advance!