Firebase HTTP Cloud Functions - Read database once

SteveEdson picture SteveEdson · May 11, 2017 · Viewed 25.8k times · Source

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.

The Firebase JS SDK says to do this using:

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

However, the Cloud functions examples have:

var functions = require('firebase-functions');

functions.database.ref('/');

But the DB reference doesn't have the method once, only onWrite (https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder). This is obviously for DB write functions, rather than HTTP functions.

Is there a correct way to read from the database once in a HTTP function? Can I use the normal Firebase SDK, or is there a better way?

Thanks.

Answer

MGR Programming picture MGR Programming · Jun 1, 2017

I found the solution in combining the answer here on how to get the parameter and an answer from Michael Blight to How to run query from inside of Cloud function?

The answer there also shows what is required to use firebase-admin.

The following works for me when calling my-project.firebaseapp.com/event/123/.

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

admin.initializeApp(functions.config().firebase);

exports.showEvent = functions.https.onRequest((req, res) => {
    const params = req.url.split("/");
    const eventId = params[2];
    return admin.database().ref('events/' + eventId).once('value', (snapshot) => {
        var event = snapshot.val();
        res.send(`
            <!doctype html>
            <html>
                <head>
                    <title>${event.name}</title>
                </head>
                <body>
                    <h1>Title ${event. name} in ${event.city}</h1>
                </body>
            </html>`
        );
     });
});