Wednesday, 19 April 2017

Cloud function for sending notification not working

I am trying to send a notification to "PLAYER 2" when a new game is added. Here is my code:

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


exports.sendNewGameNotification= functions.database.ref('/GAMES/{gameId}/PLAYER 2').onWrite(event => {
const player2uid = event.params.val;

const getDeviceTokensPromise = admin.database().ref(`/USERS/${player2uid}/fcm`).once('value');

return Promise.all([getDeviceTokensPromise]).then(results => {

const tokensSnapshot = results[0];
// Notification details.
const payload = {
  'data': { 
        'title': "Tienes una nueva partida"
  }
};

// Listing all tokens, error here below.
const tokens = Object.keys(tokensSnapshot.val());

// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
  // For each message check if there was an error.
  const tokensToRemove = [];
  response.results.forEach((result, index) => {
    const error = result.error;
    if (error) {
      console.error('Failure sending notification to', tokens[index], error);
      // Cleanup the tokens who are not registered anymore.
      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);
});
});
});

When it is executed, in the firebase console says

 TypeError: Cannot convert undefined or null to object

Like if it were null but the fcm is there, what am i doing wrong?



via Martin De Simone

No comments:

Post a Comment