Облачные функции Firebase - Не удается прочитать свойство 'val' из неопределенного - PullRequest
0 голосов
/ 27 июня 2018

Итак, вот ошибка;

TypeError: Невозможно прочитать свойство 'val' из неопределенного at exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:14:19) на объекте. (/User_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27) на следующем (родном) в /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71 в __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12) в cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36) по адресу /var/tmp/worker/worker.js:728:24 at process._tickDomainCallback (internal / process / next_tick.js: 135: 7)

и вот мой код:

exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {

  const user_id = context.params.user_id;
  const notification = context.params.notification;

  console.log('We have a notification to send to : ', user_id);

  if(!context.data.val()){
    return console.log('A notification has been deleted from the database:', notification_id);
  }

  const deviceToken = admin.database().ref(`/Users/${user_id}/deviceToken`).once('value');

  return deviceToken.then(result => {

    const token_id = result.val();

    const payload = {
      notification: {
        title : "Friend Request",
        body : "You've receieved a new Friend Request",
        icon : "default"
      }
    };

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

      console.log('This is the notification Feature');

    });

  });



});

Ответы [ 2 ]

0 голосов
/ 21 октября 2018

вместо

const token_id = result.val();

попробуй

const token_id = result.after.data();
0 голосов
/ 27 июня 2018

Вместо context.data.val() используйте change.after.exists()

Пожалуйста, проверьте эту функцию:

exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {
  const user_id = context.params.user_id;
  const notification = context.params.notification_id;
  console.log('We have a notification to send to : ', user_id);
  if (!change.after.exists()) { 
    console.log('A notification has been deleted from the database:', notification); 
    return null;
  }
  const deviceToken = admin.database().ref(`/Users/${user_id}/deviceToken`).once('value');
  return deviceToken.then(result => {
    const token_id = result.val();
    const payload = {
      notification: {
        title: "Friend Request",
        body: "You've receieved a new Friend Request",
        icon: "default"
      }
    };
    return admin.messaging().sendToDevice(token_id, payload).then(response => {
      console.log('This is the notification Feature');
    });
  });
});
...