使用Firebase云消息发送通知

时间:2018-11-22 17:03:46

标签: javascript firebase firebase-cloud-messaging

当我使用我部署到我的Firebase函数中的以下功能在我的应用中向用户发送好友请求时,我正在尝试通过Firebase云消息向用户发送通知

'use strict'

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

exports.sendNotification = functions.database.ref('/Notifications/{user_id}/{notifications_id}').onWrite(event => {
	const user_id = event.params.user_id;
	const notifications = event.params.notifications;

	console.log('This User Id is :', user_id);
});

但是当它尝试发送通知时,我的功能日志中出现以下错误

 sendNotification
	

TypeError: Cannot read property 'user_id' of undefined
    at exports.sendNotification.functions.database.ref.onWrite.event (/user_code/index.js:8:30)
    at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20)
    at /var/tmp/worker/worker.js:758:24
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

1 个答案:

答案 0 :(得分:0)

您必须添加上下文并从那里获取参数。试试:

            ..'use strict'

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

            exports.sendNotification = functions.database
              .ref('/Notifications/{user_id}/{notifications_id}')
              .onWrite((event, context) => {

                   const user_id = context.params.user_id;
                   const notifications = context.params.notifications;

                  console.log('This User Id is :', user_id);
            });