David Massey
David Massey

Reputation: 319

Firebase cloud function that writes to database writes multiple times and never returns

I'm trying to create a cloud function to write to a firebase db. It's supposed to be really simple. I want to write and return a 200. The example they give does a redirect in the then callback, but I don't want to redirect. Unfortunately, my function hangs indefinitely and writes the same message to the db 3,4,5,6 times.

I'm pretty sure I am doing the return incorrectly. I tried to return res.status = 200 from the then callback, but that didn't work either.

This is what I have currently:

exports.createEvent = functions.https.onRequest((req, res) => {
    const name = req.query.name;
    const description = req.query.description;
    const location = req.query.location; //json? lat/lng, public,
    const date = req.query.date;

    // Push the new message into the Realtime Database using the Firebase Admin SDK.
    return admin.database().ref('/Event')
        .push({name : name, description : description, location : location, date : date});
});

Upvotes: 0

Views: 322

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83113

I would suggest you watch the official Video Series on Cloud Functions (https://firebase.google.com/docs/functions/video-series/) and in particular the first video on Promises titled "Learn JavaScript Promises (Pt.1) with HTTP Triggers in Cloud Functions".

You will see that for an HTTTS Cloud Function you have to send a response to the client (watch the video at 8:50).

Therefore the following modifications to your code should do the trick:

exports.createEvent = functions.https.onRequest((req, res) => {
    const name = req.query.name;
    const description = req.query.description;
    const location = req.query.location; //json? lat/lng, public,
    const date = req.query.date;

    // Push the new message into the Realtime Database using the Firebase Admin SDK.
    admin.database().ref('/Event')
        .push({name : name, description : description, location : location, date : date})
        .then(ref => {
           res.send('success');
        })
        .catch(error => {
           res.status(500).send(error);
        })
});

Upvotes: 1

Related Questions