Home > OS >  How to fetch data from firestore in cloud function
How to fetch data from firestore in cloud function

Time:11-02

I need to fetch the user token from the firestore in a cloud function.

the user token was stored as follows:

void saveToken(String token) async {
    await FirebaseFirestore.instance
        .collection("User tokens")
        .doc(userId)
        .set({'token': token});
  }

here is the goal. When a message is created on the collection 'chat messages', grab the "Chat id" value and the user who sends the message "User id".

query the collection "chat" using the "Chat id" value, grab the "Job users data" value (this is an array with two objects, each object contains the users involved in the chat (userName,userId) ).

from the "Job users data", I need to grab the userId of the member who should be receiving the message.

query "User tokens" collection to grab the "token" value. use the "token" value, to send a notification to

here is my cloud function: as you see, I have hardcoded the token to see if I could send that device a notification.... that works perfect. now I need to to make this dynamic...

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const { database } = require("firebase-admin");

// eslint-disable-next-line max-len
const tokens = ["JNKDNASNDAUIU324234....."];

admin.initializeApp();

// exports.onCreate = functions.firestore
//     .document("chat/{docId}")
//     .onCreate((snapshot, context) => {
//       console.log(snapshot.data());
//       console.log("fake data");
//     });

exports.onChatMessageCreate = functions.firestore
    .document("chat messages/{docId}")
    .onCreate( (snapshot, context) => {
      console.log(snapshot.data());

     // fetch user to send message to
     // admin.database().ref("/")

      const payload = {
        // eslint-disable-next-line max-len
        notification: {title: snapshot.data()["userName"], body: snapshot.data()["Chat message"], sound: "default"},
        // eslint-disable-next-line max-len
        data: {click_action: "FLUTTER_NOTIFICATION_CLICK", message: "Sample Push Message"},
      };

      try {
        admin.messaging().sendToDevice(tokens, payload);
        console.log("NOTIFICATION SEND SUCCESSFULLY");
      } catch (e) {
        console.log("ERROR SENDING NOTIFICATION");
        console.log(e);
      }
    });

So all i need to know is how to query collections from a cloud function

CodePudding user response:

There are 2 ways to query a collection in Node.js. either through then() or async/await.

to query using promise:

const collectionRef = admin.firestore().collection("yourCollection");
 return collectionRef.get().then((collections) => {
//you can now use your collections here
});

using async/await:

  const collectionRef = admin.firestore().collection("yourCollection");
    const collections = await collectionRef.get();

  • Related