Inv4si0n
Inv4si0n

Reputation: 5

Fetching Realtime Database in Cloud Function return the wrong object

I'm trying to fetch data from my Realtime database but when I do, it return my this object:

{"domain":{"domain":null,"_events":{},"_eventsCount":3,"members":[]}} instead of something like this: {0: 'user1', 1: 'user2'}.

There is a screen from my Realtime database:

realtime databse

My code:

const functions = require("firebase-functions");

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

exports.getProductTypeUpdate = functions.database
    .ref("Products/{product}/type")
    .onUpdate((snapshot, context) => {
      const type = snapshot.after.val();
      console.log("Product type created: " + type);
      const users = admin.database().ref("Notif/type/" + type)
          .once("value").then((snapshot) => {
            return snapshot.val();
          }).catch((error) => {
            console.log("Error sending message:", error);
            return false;
          });
      console.log("Users fetched are: " + JSON.stringify(users));
      const result = {etat: "create", users: users};
      console.log("Final result is: " + JSON.stringify(result));
      return result;
    });

And the "error" (it's write in french but it's not important):

wrong object

Thank you for help !

Upvotes: 0

Views: 56

Answers (2)

Inv4si0n
Inv4si0n

Reputation: 5

I did it but I think my Node.js version was not able to run ES6, I get messages like "Unexpected token", so I did that and now it works:

exports.getProductTypeUpdate = functions.database
.ref("Products/{product}/type")
.onUpdate((snapshot, context) => {
  // on récupère le type du produit
  const type = snapshot.after.val();
  console.log("Le type du produit créé est: " + type);
  // on récupère les utilisateurs interresse par le type d'objet
  admin.database().ref("Notif/type/" + type)
      .once("value").then((snapshot) => {
        const users = snapshot.val();
        console.log("Les utilisateurs dans " +
        "le snapshot sont:" + snapshot.val());
        console.log("Les utilisateurs tirés sont: " + users);
        // Retourne les utilisateurs à notifier et l'état de la requête
        const result = {state: "create", users: users};
        console.log("Le résultat final est: " + JSON.stringify(result));
        return result;
      }).catch((error) => {
        console.log("Error sending message:", error);
        return false;
      });
});

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

The problem is that your users variable is actually a Promise. To log it inside the code, you have to either await it, or use then().

It's probably easiest to start using async and await here, which would make your code look like this:

exports.getProductTypeUpdate = functions.database
  .ref("Products/{product}/type")
  .onUpdate(async (snapshot, context) => {
          // 👆
    const type = snapshot.after.val();
    try {
      const snapshot = await admin.database().ref("Notif/type/" + type).once("value");
      let users = snapshot.val();
      const result = {etat: "create", users: users};
      return result;
    }
    catch (error) {
      console.log("Error sending message:", error);
      return false;
    }
  });

I also recommend reading the Firebase documentation on sync, async, promises and how to terminate functions, and the MDN documentation on async/await.

Upvotes: 1

Related Questions