Home > other >  Firebase functions: getting document data inside a function
Firebase functions: getting document data inside a function

Time:08-10

im making a type of chat app. Im trying to write a firestore function that listens to a specific document that, when updated, will trigger the function to send a push notification to a specific user. However, im receiving an error. So far, i have:

export const messageListener = functions.firestore
    .document("stingrayMessageListener/stingrayMessageListener")
    .onWrite(async (change) => {
      const beforeData = change?.before?.data();
      const afterData = change?.before?.data();
      if (beforeData?.receiverId!=afterData?.receiverId) {
        const docRef = admin.firestore().doc("users/${afterData?.receiverId}");
        const docSnap = await docRef.get();
        const payload = {
          notification: {
            title: "New message!",
            body: "${afterData?.senderName} has sent you a message!",
          },
          data: {
            body: "message",
          },
        };
        admin.messaging().sendToDevice(docSnap.data()?.token, payload);
      }
    });

This function is spitting out the following error:

Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array

Im pretty sure this is implying that docSnap() is returning as null, because token is a field on all user documents. Am I doing something wrong?

CodePudding user response:

So, turns out it was a very simple solution. In Typescript, you can dont use "" to use a variable in a string. You use ``.

CodePudding user response:

In addition to using template literals in your document paths as you answered, both beforeData and afterData are assigned to change?.before?.data(), meaning your function won't send notifications to any device:

const beforeData = change?.before?.data();
const afterData = change?.before?.data();
if (beforeData?.receiverId != afterData?.receiverId) {
    //above condition won't be true
...

You'd only need to use the after property holding the changed document.

const afterData = change?.after?.data();

Let me know if this was helpful.

  • Related