Home > other >  Automatically generating cloud functions when group created
Automatically generating cloud functions when group created

Time:07-17

What is the best approach for my case? A user creates a messaging group in my app. Then the group will get its own auto id. Now I want to use cloud func from firebase to check for new messages and to do a push notification.

The code below checks if a group is created and send the push notification. But this only works when I know the generated auto id and post it manually in the code below. How can I solve this issue? Should my App create for each group its own cloud function? Would this not be too much? Or can I use somehow a wildcard?

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

   exports.Push = functions.database.ref('/placeID/theGeneratedIdComesHere/{messageID}/')
   .onCreate((snapshot, context) => {
 
      var nameUser = String(snapshot.val().userName)
      var textUser = String(snapshot.val().userComment)

      var topic = 'weather';
      const payload = {
          notification: {
              title: nameUser,
              body: textUser,
              badge: '1',
              sound: 'default'
          }
     };
  
     admin.messaging().sendToTopic(topic,payload);
   })

CodePudding user response:

You can make the group ID a parameter on your Cloud Function declaration:

exports.Push = functions.database.ref('/placeID/{groupID}/{messageID}/')

Then you can access that group ID in your functions code with:

const groupID = context.params.groupID;

And then you can use that value in your code to make it to what this specific group needs.

  • Related