Firebase TypeError: Cannot read property 'val' of undefined

后端 未结 2 1729
清酒与你
清酒与你 2020-11-30 06:02

I have tried Firebase cloud function for sending a notification.My project structure

and this is the index.js,

const functions = require(\'firebase         


        
2条回答
  •  清歌不尽
    2020-11-30 06:30

    'use strict'
    
    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp(functions.config().firebase);
    
    exports.sendNotification = functions.database.ref('/NOTIFICATIONS/{UserId}/{{notification_id}').onWrite((change, context) => 
    {
        const UserId = context.params.UserId;
        const notification = context.params.notification;
    
        console.log('The user Id is : ', UserId);
    
        if(!change.after.exists())
        {
            return console.log('A Notification has been deleted from the database : ', notification_id);
        }
    
        if (!change.after.exists()) 
        {
            return console.log('A notification has been deleted from the database:', notification);
            return null;
        }
    
        const deviceToken = admin.database().ref(`/USER/${UserId}/device_token`).once('value');
    
        return deviceToken.then(result => 
        {
            const token_id = result.val();
            const payload = {
                notification : {
                    title : "Friend Request",
                    body : "You've received a new Friend Request",
                    icon : "default"
                }
            };
    
            return admin.messaging().sendToDevice(token_id, payload).then(response => {
    
                console.log('This was the notification Feature');
            });
        });
    });
    

提交回复
热议问题