Firebase功能参考错误

时间:2018-07-24 21:56:37

标签: node.js firebase google-cloud-functions

我正在使用Firebase函数向每个用户发起通知推送。该函数如下所示:

  'use strict'

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

exports.sendNotification = functions.database.ref('/Notifications/{recieverid}/{notificationid}')
    .onWrite((data,context) =>
    {
        console.log(data);
    const recieverid = context.params.recieverid;
    const notificationid = context.params.notificationid;


    const deviceToken = admin.database().ref(`/users/${recieverid}/token`).value;

    return deviceToken.then(result=> 
    {
        const token = result.val();
        const payload = 
        {
            notification: 
            {
                title: "You've been caught!",
                body: "Somebody likes you as much as you like them",
                icon:"default"
            }
        };
      return admin.messaging().sendToDevice(token, payload);

    });
});

并且我通过日志收到以下错误:

TypeError: Cannot read property 'then' of undefined
    at exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:17:20)
    at Object.<anonymous> (/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:728:24
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

关于为什么出现上述错误以及更重要的是如何解决该错误的任何想法?是JS的新功能,但不是Java的功能。

詹姆斯

2 个答案:

答案 0 :(得分:1)

const reciever_id = event.params.reciever_id;
const notification_id = event.params.notification_id;
console.log('We have a notification to send to: ', reciever_id);

if(!event.data.val());

错误是因为未声明名为event的变量。也许您要使用datacontext而不是event,因为函数会返回它们onWrite

答案 1 :(得分:0)

找到了答案,代码如下:

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

exports.sendNotification = functions.database
.ref('/notifications/{recieverid}/{notificationid}')
.onWrite((snapshot,context) => {
    console.log(snapshot);
    const recieverid = context.params.recieverid;
    const notificationid = context.params.notificationid;

    return admin.database().ref(`/users/${recieverid}/token`).once('value', function(snapshot) {
        const token = snapshot.val();
        const payload = 
        {
            notification: 
            {
                title: "SomeTitle",
                body: "SomeBody",
                icon: "default"
            }
        };
        return admin.messaging().sendToDevice(token, payload).then(function(response){
            return console.log("Successfully sent message:", response)
        });
    });
});