I'd like to perform a query on my database once a cloud function on my Firebase app is called.

Let's say I have a certain trigger on the database, consider the example provided in the get started guide on Firebase.

// Listens for new messages added to /messages/:pushId/original and creates an
// uppercase version of the message to /messages/:pushId/uppercase
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
  .onWrite(event => {
      // Grab the current value of what was written to the Realtime Database.
      const original = event.data.val();
      console.log('Uppercasing', event.params.pushId, original);
      const uppercase = original.toUpperCase();
      // I'D LIKE TO PERFORM A QUERY HERE, JUST A SIMPLE RETRIEVE BASED ON THE ID PROVIDED
     // You must return a Promise when performing asynchronous tasks inside a Functions such as
     // writing to the Firebase Realtime Database.
     // Setting an "uppercase" sibling in the Realtime Database returns a Promise.
     return event.data.ref.parent.child('uppercase').set(uppercase);
});

Which modules should I import, if any? How can I perform the query on the DB?

Thank you in advance for your answer!


Solution 1:

You can use the Node.js Admin SDK for this:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.makeUppercase = functions.database()
  .ref('/messages/{pushId}/original')
  .onWrite(event => {
    return admin.database().ref('/other')
      .orderByChild('id').equalTo(event.params.pushId)
      .once('value').then(snapshot => {
        // there, I queried!
      });
  });