elition
elition

Reputation: 71

Firebase Cloud function Messaging keep sending notification until user open it

I'm stuck on an issue. I'm using Firebase Cloud functions to send a push notification. I use Topic subscription.

Here is the code :

export const sendNotification = functions.https.onRequest((request, response) => {
  return cors() (request, response, async () => {
    const { senderID, receiverID, messageSent } = request.body;

    const db = admin.database();

    try {
      const ref = db.refFromURL(`https://firebase-url/recentchats/${receiverID}/${senderID}`)
      const data = await ref.once("value");

      functions.logger.warn("DATA : ", data.val());

      if (messageSent === data.val().message && !data.val().read) {
        const senderName = data.val().sender;
        const notification: MessagingPayload = {
          notification: {
            title: `Nouveau message de ${senderName}`,
            body: messageSent,
          },
          data: {
            route: `/app/tabs/chat/${senderID}/${senderName}`
          }
        };

        functions.logger.warn(`${senderName} a envoyé le message : ${messageSent}`);
        
        const result = await admin.messaging().sendToTopic(receiverID, notification);

        functions.logger.warn(result);

        return null;
      } else {
        return null;
      }
    } catch (error) {
      functions.logger.error("ERROR : ", error);
      return error;
    }
  });
});

My problem is that the user keep receiving the same notification every minute until he decides to open one...

The log in firebase that keep repeating :

enter image description here

I don't understand why. I looked in the documentation but I didn't find any solution for my problem.

I hope that someone will have a clue about this issue.

Thanks everyone

Upvotes: 0

Views: 137

Answers (1)

elition
elition

Reputation: 71

I found the solution here : https://firebase.google.com/docs/functions/terminate-functions

Because I used an HTTP cloud function, I need to send a response to the client. I didn't do that so the function fall in timeout and I think Firebase retry the process that's why I keep receiving the same notification.

So the solution is to use

response.send("ok");

instead of

return null;

Upvotes: 1

Related Questions