Firebase HTTP Cloud Functions - Read database once

前端 未结 2 1802
死守一世寂寞
死守一世寂寞 2020-11-29 02:33

I have a Firebase HTTPs function. The function needs to read a value from a Firebase database based on the query parameter, and return a result based on this data.

T

2条回答
  •  庸人自扰
    2020-11-29 03:05

    You're confusing two parts:

    • the firebase-functions module, which contains the logic to trigger based on database calls with functions.database.ref('/path').onWrite().
    • the firebase-admin module, which allows your function to call into the database.

    Since you have a HTTP function, you should trigger as the documentation for HTTP functions shows:

    exports.data = functions.https.onRequest((req, res) => {
      // ...
    });
    

    Then in your function, you access the database as the documentation for the Admin SDK shows:

    return admin.database().ref('/users/' + userId).once('value').then(function(snapshot) {
      var username = snapshot.val().username;
      // ...
    });
    

    So in total:

    exports.date = functions.https.onRequest((req, res) => {
      admin.database().ref('/users/' + userId).once('value').then(function(snapshot) {
        var username = snapshot.val().username;
        res.status(200).send(username);
      });
    });
    

    Note that this is a tricky pattern. The call to the database happens asynchronously and may take some time to complete. While waiting for that, the HTTP function may time out and be terminated by the Google Cloud Functions system. See this section of the documentation.

    As a general rule I'd recommend using a Firebase Database SDK or its REST API to access the database and not rely on a HTTP function as middleware.

提交回复
热议问题