Whyser
Whyser

Reputation: 2247

Update value once write completes in Cloud Function

I'm trying to update one value after a write completes (in a Cloud Function) but it just wont work (I'm sure this is a stupidly simple problem). Code below:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const firebase = require('firebase');

 admin.initializeApp(functions.config().firebase);
 exports.createMessage = functions.https.onRequest((request, response) => {
        const json = JSON.parse(request.query.json); // == "{'start':0, 'end':0}"
        json.start = firebase.database.ServerValue.TIMESTAMP;
        admin.database().ref('/messages/').push(json).then(snapshot => {

            //Here is the problem. Whatever I try here it won't work to retrieve the value.
            //So, how to I get the "start" value, which has been written to the DB (TIMESTAMP value)?
            var startValue = snapshot.ref.child('start').val();

            snapshot.ref.update({ end: (startValue + 85800000) }).then(snapshot2=>{
                response.redirect(303, snapshot.ref);
            });
        });
 });

Is the problem that I'm using admin.database()?

Upvotes: 0

Views: 231

Answers (2)

Whyser
Whyser

Reputation: 2247

I'm not sure if there's a bug in Firebase or if I'm using it wrong, but if I try to call any method on the snapshot-reference I will only get an error saying: TypeError: snapshot.xxx is not a function where xxx is the function name i try to use (for example: child(...), forEach(...), etc).

However, the following seems to fix the issue with the snapshot:

admin.database().ref('/messages/').push(json).once('value').then(snapshot => {

instead of:

admin.database().ref('/messages/').push(json).then(snapshot => {

My uneducated guess is that the then-promise, for the push-function returns some faulty snapshot since the only thing that seems to work is snapshot.key.

Also, if I'm not mistaken, doesn't my solution make two reads now, instead of one? Since push will write and then (supposedly) read and return the written value and then I read it once more with once(value).

Does anyone has any further insights into this problem?

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317352

This code:

var startValue = snapshot.ref.child('start').val();

doesn't actually retrieve any values. Take a look at the docs for DataSnapshot. Reach into that snapshot directly with child() - you don't need the ref. Maybe this is what you meant?

var startValue = snapshot.child('start').val();

Upvotes: 3

Related Questions