skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

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


  2. 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 which holds the changed document.

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

    Let me know if this was helpful.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search