Я работаю с уведомлениями Firebase, используя node.js. После компиляции, когда я отправляю запрос другому пользователю приложения (запрос отправляет уведомление), журнал firebase показывает ошибку:
TypeError: Cannot read property 'receiver_id' of undefined at exports.sendNotification.functions.database.ref.onWrite.event (/user_code/index.js:12:36) at Object. (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27) at next (native) at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71 at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12) at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36) at /var/tmp/worker/worker.js:700:26 at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Код Index.js:
'use strict'
const functions = require('firebase-functions');
const admin = require ('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification =
functions.database.ref('/Notifications/{receiver_id}/{notification_id}')
.onWrite(event =>
{
const receiver_id = event.params.receiver_id;
const notification_id = event.params.notification_id;
console.info('We have a notification to send to :', receiver_id);
if (!event.data.val())
{
return console.info('A notification has been deleted from the database: ', notification_id);
}
const deviceToken = admin.database().ref(`/Users/${receiver_id}/device_token`).once('value');
return deviceToken.then(result =>
{
const token_id = result.val();
const payload =
{
notification:
{
title: "Friend Request",
body: "you have received a new friend request",
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id, payload)
.then(response =>
{
console.info('This was the notification feature.');
});
});
});
Я прочитал о новых API на сайте:
https://firebase.google.com/docs/functions/beta-v1-diff
Я думаю, что мне нужно изменить событие на контекст, но я не знаю, как это сделать. Кто-нибудь знает, в чем проблема? Спасибо за любую помощь :)
Документация Firebase по новым data и context показывает, где сейчас находится params:
The
contextparameter provides information about the function's execution. Identical across asynchronous functions types, context contains the fieldseventId,timestamp,eventType,resource, andparams.
Итак, чтобы избавиться от этой ошибки, вам нужно изменить первый бит вашей функции на:
exports.sendNotification =
functions.database.ref('/Notifications/{receiver_id}/{notification_id}')
.onWrite((data, context) =>
{
const receiver_id = context.params.receiver_id;
const notification_id = context.params.notification_id;
...
Вам нужно будет внести и другие аналогичные изменения. Если вам сложно сделать их самостоятельно, я рекомендую вам проверить, откуда вы взяли код.
Спасибо за этот образец. Что-то странное. Я еще не щелкнул, но у меня недостаточно очков репутации для отображения этой операции.
Хорошо, это решает эту ошибку и дает мне другую. Как Вы сказали, я должен изменить некоторые команды. Однако спасибо за ответ. Это действительно полезно