degenPenguin
degenPenguin

Reputation: 725

Cloud Function failing to access Firebase Database

So I am trying to very simply read and update data from my Firebase Database, and it is giving me an error.

"Error: Could not handle request"

I followed the instructions to initialize my app from Google's tutorial I deploy my methods as suggested firebase deploy --only functions And I get the following response:

i  deploying functions
i  functions: ensuring necessary APIs are enabled...
✔  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (63.07 KB) for uploading
✔  functions: functions folder uploaded successfully
i  functions: current functions in project: addMessage, helloWorld, now, weather, weather2
i  functions: uploading functions in project: weather
i  functions: updating function weather...
✔  functions[weather]: Successful update operation.
Function URL (weather): https://us-central1-*****.cloudfunctions.net/weather

Interestingly, their example method "addMessage" works fine:

// Take the text parameter passed to this HTTP endpoint and insert it into the
// Realtime Database under the path /messages/:pushId/original
exports.addMessage = functions.https.onRequest((req, res) => {
  // Grab the text parameter.
  const original = req.query.text;
  // Push the new message into the Realtime Database using the Firebase Admin SDK.
  admin.database().ref('/messages').push({original: original}).then(snapshot => {
    // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
    res.redirect(303, snapshot.ref);
  });
});

However, when I try to make my own method using this tutorial on updating data instead of pushing data, I run into problems Any help on this is greatly appreciated, I have been working at this for hours.

how my data is structured:

- My code:

exports.weather = functions.https.onRequest((request, response) => {
  admin.database.ref('/weather').once('value').then(snapshot => {
    var temp = snapshot.child('temp').val();
    var time = snapshot.child("time").val()
    var diff = diff_minutes(Date().getTime(), time)
    //If the last request >=5 minutes, call DarkSky API & Update database
    if (diff >= 5) {
       var updates = {
          time: NEW_TIME,
          temp: NEW_TEMPERATURE
        }
        snapshot.update(updates)
        response.send(updates);
    }
     else {
      response.send(temp)
    }
  })
});

function diff_minutes(second_time, first_time) {
  var diff =(second_time - first_time) / (1000 * 60);
  return Math.abs(Math.round(diff));
}

Any ideas?

Upvotes: 0

Views: 987

Answers (2)

degenPenguin
degenPenguin

Reputation: 725

Here is my final code with Dark Sky's API and all (thank you to everyone who helped!):

This code, on HTTP request, checks the time of the last API call to Dark Sky API's request for a specific location, then uses the previous results if within the last 5minutes, or updates the results if longer.

data

exports.weather = functions.https.onRequest((req, res) => {
  admin.database().ref('/weather').once('value').then(snapshot => {
      var temp = snapshot.child('temp').val();
      var time = snapshot.child("time").val();
      var diff = diff_minutes(Date.now(), time);
      var current = {
        time: time,
        temp: temp
      }
      if (diff >= 5) {
        DarkSkyApi.loadCurrent(position).then(result => {
          var updates = {
            time: result.time,
            temp: result.temperature
          }
          snapshot.ref.update(updates).then(() => {
            res.send(current);
          }).catch(error => {
              console.error('Update failed:', error);
              res.send('Update failed'); // or some error status of your choice
          });
        });
      }
      else {
        res.send(current);
      }
  });
});
    function diff_minutes(second_time, first_time) {
      var diff =(second_time - first_time) / (1000 * 60);
      return Math.abs(Math.round(diff));
    }

Upvotes: 0

Bob Snyder
Bob Snyder

Reputation: 38319

This code to update the database and send the response is not correct:

snapshot.update(updates);
response.send(updates);

snapshot is an instance of DataSnapshot and does not have an update() method.

Replace those two statements with:

snapshot.ref.update(updates).then(() => {
  response.send(updates);
}).catch(error => {
    console.error('Update failed:', error);
    response.send('Update failed'); // or some error status of your choice
});

Also:

Change admin.database.ref to admin.database().ref

Change Date().getTime() to Date.now()

Upvotes: 3

Related Questions