How to reference userid and issue a notification in firebase

Asked

Viewed 24 times

0

I’m having the following structure of the real time database:

inserir a descrição da imagem aqui

And I am trying to create a trigger so that whenever a message is added in user003 I send a notification through FCM my function is not working

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

exports.fcmSend = functions.database.ref('/messages/{userId}/{messageId}').onCreate(event => {

  console.log('event', event)

  const message = event.after.val()
  const userId  = event.params.userId
  const payload = {
        notification: {
          title: message.title,
          body: message.body,
          icon: "https://placeimg.com/250/250/people"
        }
      };


   admin.database()
        .ref(`/fcmTokens/${userId}`)
        .once('value')
        .then(token => token.val() )
        .then(userFcmToken => {
          return admin.messaging().sendToDevice(userFcmToken, payload)
        })
        .then(res => {
          console.log("Sent Successfully", res);
        })
        .catch(err => {
          console.log('err', err);
        });

});

1 answer

0

I would change these lines here, take a look at the log the messages

Return admin.database() . ref(/fcmTokens/${userId}) .Once('value') . then(snapshot => { console.log("token", snapshot.val() ); Return admin.messaging(). sendToDevice(snapshot.val(), payload) }) . then(res => { console.log("Sent Successfully", res); }) . catch(err => { console.log('err', err); });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.