Twice Triggered: Firebase Cloud Function HTTPS Call

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!

Answer №1

The issue has been resolved. A mix of inaccurate information from the Firebase Console Logs (repeated entries) and improperly nested for loops in the incorrect order led to the situation of double triggering.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deactivate click events in the container div

Here is the html code snippet that I am working with: <div class="parent" ng-click="ParentClick()"> . . . <div class="child" ng-click="ChildClick()"> Some Text </div> </div> When clicking on Som ...

Having trouble with your Bootstrap 4 Dropdown Menu?

I attempted to implement the dropdown menu example from Bootstrap 4, but unfortunately it does not seem to be working as expected. The dropdown menu does not appear when clicked. <li class="nav-item dropdown"> <a class="nav-link dropdown-to ...

Alter the style of a div by clicking on a button

Can the background image of a div be changed by selecting a button outside of the div? For example: HTML <div id="change"></div> <div id="buttons"> <button class="button1">this</button> <button class="button2"> ...

Ruby on Rails and JSON: Increment a counter with a button press

How can I update a count on my view without refreshing the page when a button is clicked? application.js $(document).on('ajax:success', '.follow-btn-show', function(e){ let data = e.detail[0]; let $el = $(this); let method = this ...

Tips on managing authentication flow in React and Firebase when waiting for a cookie before setting the authContext and login state

I am facing an issue with my code. I have a createUser function that communicates with an express server via axios to create a Firebase authenticated user, generate a token, and send the token back to the user as a cookie. Additionally, I have a getLogged ...

Managing selected ticket IDs in a table with AngularJS

I have a table that includes options for navigating to the next and previous pages using corresponding buttons. When I trigger actions for moving to the previous or next page (via controller methods), I store the IDs of checked tickets in an array $scope. ...

Avoid using `@typescript-eslint/no-floating-promises` when using a `const` function

Can anyone help me understand why the @typescript-eslint/no-floating-promises rule works with some async functions but not all? To my understanding, these two functions should be equivalent: const getUser = async (userId: string): Promise<User> => ...

Is it possible to combine NodeJs + Express + MongoDb with Firebase?

Although I'm familiar with the MEAN solution stack for web app and API development, I've found Google Firebase to be more convenient due to its integrated database, storage, authentication, and hosting capabilities. I especially appreciate Fireb ...

Can you make two columns in CSS that are left floated and maintain their original order?

While the title may not provide much clarity, I am struggling to put into words exactly what I am trying to achieve. I have created a layout in Photoshop which I have shared below to help illustrate my goal. Essentially, I have a blog that displays my sto ...

How can I resolve the issue of using string values for items inside v-autocomplete, but needing them to be numbers in v-model?

I am working with a v-autocomplete component <v-autocomplete v-model="addressRegion" :items="selectLists.regions" item-value="key" item-text="value" ></v-autocomplete> The AddressRegion is curren ...

Rows in the table mysteriously vanish when you switch to the following page

I am a beginner with React and I am currently using an addrow method to populate a table that I created using {this.state.rows.map}. The table successfully displays the values from the input fields. However, when I navigate away using the continue button a ...

Exploring the world of MVC4: Enhancing user experience with client-side

Solution: The answer provided by @www.innovacall.com is correct, I initially misunderstood it but now it works perfectly. Thank you for the help. Initial issue: I have been struggling with finding a solution to my problem. In my project, there is a mod ...

Node.js, PHP, and the Express framework

I have a project where I need to develop a to-do list and a form that allows users to upload png files using Node.js. Currently, I am using the following packages: { "name": "todo", "version": "0.0.1", "private": true, "dependencies": { "ejs": ...

What is the best way to fetch data before a component is rendered on the screen?

I am facing an issue with fetching data from a local server in Node. When I try to render the component, the array 'users' from the state appears to be empty, resulting in no users being displayed on the screen as intended. What's strange is ...

Utilizing a try/catch block for validating a JSON file is ineffective

I'm attempting to verify if a received string is JSON and I experimented with the code below: try { JSON.parse(-10); // Also tried with "-10" }catch(e) { console.log('inside catch'); } Surprisingly, the code never enters the catch ...

Add a trash can or delete icon within every row of a table using Vue.js

I am new to vue.js and I'm struggling to implement a trash icon in each row of a table for deleting rows. Additionally, I'm trying to make the input of a cell act as a dropdown menu or list within the table rows. I recently came across this scrip ...

how can you activate a modal without relying on bootstrap?

Could anyone suggest a more efficient way to create a pop-up modal triggered by a button click without relying on bootstrap? I've attempted different methods but haven't achieved the desired result. Here's a sample plunker for reference. Any ...

The JavaScript function for converting a date to a local string in the format of DD MMM YYYY is causing an error message in the browser console stating that it is not a valid function

I am encountering an issue with formatting a date string. The date is currently in the format 2021-03-31T00:00:00, and I need it to be displayed as 31 Mar 2021. In my TypeScript code, I attempted to use the following function: const formattedDate = i.Susp ...

Display the latest distinct records in Vue.js

I've hit a roadblock in my project. @StephenThomas kindly assisted me with this issue: Vue.js only show objects with a unique property but I still need to make some adjustments. My current task involves creating a leaderboard for a game using Firest ...

What is the process for converting JSON data into an array of model objects?

In my C#/ASP.Net project utilizing WebAPI2, there is an API endpoint that returns an array of JSON objects in response to a GET request. Serialization takes place automatically using a Model of the native object when an OK HttpActionResult typed for an IEn ...