Sunday, 11 June 2023

How to create an array of payloads for individual users instead of one payload for push notifications

I can't find any documentation to help me in this situation. I wrote a cloud function that sends a payload to users belonging to a certain group when a new document is created. Users now want to choose their own notification sounds. So I added a picker in their settings screen where they can choose a sound and it stores it in firestore with their user settings under the variable "pushnotificationsound" the .wav files are stored on the device itself locally. I tried to replace the sound variable in the payload with "userData.pushnotificationsound" but I think everyone is getting the same payload because everyone is getting the same sound. Here is my current cloud function:

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

exports.demopush = functions.firestore.document('Demo Alarms/{documentId}').onCreate(async (snapshot, context) => {
  const post = snapshot.data();
  const Type = post.Type;
  const code = post.Code;
  const address = post.Address;

  const usersSnapshot = await admin.firestore()
    .collection('users')
    .where('agency', '==', 'demo')
    .get();

  const tokens = [];
  usersSnapshot.forEach(doc => {
    const agency = doc.data().agency;
    const token = doc.data().push_token;
    if (agency && agency === 'Demo' && token) {
      tokens.push(token);
    }
  });

  if (tokens.length === 0) {
    console.log('No users to send notification to.');
    return;
  }

  const payload = {
    notification: {
      title: 'DEMO DEPARTMENT',
      body: `${Type} ${code} at ${address}`,
      sound: 'default',
      android_channel_id: "Alarms"
    },
    
  };

  try {
    const response = await admin.messaging().sendToDevice(tokens, payload);
    console.log('Notification sent successfully:', response);
  } catch (error) {
    console.error('Error sending notification:', error);
  }
});



from How to create an array of payloads for individual users instead of one payload for push notifications

No comments:

Post a Comment