firebase / functions-samples

Collection of sample apps showcasing popular use cases using Cloud Functions for Firebase
https://firebase.google.com/docs/functions
Apache License 2.0
12.07k stars 3.84k forks source link

Firebase function to fetch data from Firebase DB to make Push notification #298

Closed varun7952 closed 6 years ago

varun7952 commented 6 years ago

I have chat app with firebase database and Firebase cloud messaging. I can send firebase notification via console but in real scenario it should be automatic. To make automatic notification,My friend wrote Index.js (Added in cloud functions) file for me but its not sending notifications.

As per our logic function should trigger whenever there is any new entries (in any node or in any room) and fetch these values by firebase function and make post request to FCM server to make notification to receiver device (get value of receiver device from token_To).

Message
Message_From
Time
Type
token_To

Firebase database structure

Index.js

var functions = require('firebase-functions');
var admin = require('firebase-admin');

var serviceAccount = require('./demofcm-78aad-firebase-adminsdk-4v1ot-2764e7b580.json');
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://demofcm-78aad.firebaseio.com/"
})

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });
exports.setUserNode = functions.auth.user().onCreate(event => {
  // ...
});

exports.notifyMsg = functions.database.ref('/{chatroom}/{mid}/')
    .onWrite(event => {

       if (!event.data.val()) {
         return console.log('Message Deleted');
       }

       const getDeviceTokensPromise = admin.database().ref('/{chatroom}/{mid}/token_to').once('value');

       return Promise.all([getDeviceTokensPromise]).then(results => {
         const tokensSnapshot = results[0];

         if (!tokensSnapshot.hasChildren()) {
           return console.log('There are no notification tokens to send to.');
         }

         const payload = {
           notification: {
             title: 'You have a new Message!',
             body: event.data.val().Message
           }
         };

         const tokens = Object.keys(tokensSnapshot.val());

         return admin.messaging().sendToDevice(tokens, payload).then(response => {

           const tokensToRemove = [];
           response.results.forEach((result, index) => {
             const error = result.error;
             if (error) {
               console.error('Failure sending notification to', tokens[index], error);

               if (error.code === 'messaging/invalid-registration-token' ||
                   error.code === 'messaging/registration-token-not-registered') {
                 tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
               }
             }
           });
           return Promise.all(tokensToRemove);
         });
       });
});

Firebase Functions Log

How can i fetch above mentioned values of any newly added node in same room(9810012321-9810012347) or any other room(9810012321-9810012325) from database and send it to FCM to make notification

Thanks in Advance.

varun7952 commented 6 years ago

Please anyone guide me there even stackoverflow don't have answer.even with bounties StackOverflow

nicolasgarnier commented 6 years ago

Looks like you got some help on stackoverflow :)