0
votes

I am trying to do a push notification function whenever the database update sends a notification but the function gets an error at first

Error:

TypeError: Cannot read property 'val' of undefined at exports.fcmSend.functions.database.ref.onCreate.event (/srv/index.js:9:31) at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23) at /worker/worker.js:825:24 at at process._tickDomainCallback (internal/process/next_tick.js:229:7)

my function

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

1 Answers

0
votes

The onCreate() listener doesn't have an "after". Only onUpdate() and onWrite() have before and after. It should work just to do:

event.val();