13

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

and this is the index.js,

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

exports.pushNotification = functions.database.ref('/messages').onWrite( event => {
console.log('Push notification event triggered');

    const message = event.data.val();
    const user = event.data.val();
    console.log(message);
    console.log(user);

    const topic = "myTopic";
    const payload = {
        "data": {
            "title": "New Message from " + user,
            "detail":message,
        }
    };

    return admin.messaging().sendToTopic(topic, payload);
   });

The above code is misconfigured, when I deploy in Node.js, LOG in Function shows:

"TypeError: Cannot read property 'val' of undefined".

What Actually I am trying to do : I am trying to extract info from snapshot load into that index.js so that when a new child gets added to Real-time database, it should trigger a notification payload with a title and body.

In Android, I use a child listener, for listening when a new record is added

FirebaseDatabase.getInstance().getReference().child("messages")

 OnChildAdded(.....){
 if (dataSnapshot != null) {
                    MessageModel messageModel = dataSnapshot.getValue(MessageModel.class);
                    if (messageModel != null) {
                            // do whatever
                           }
                   }

But in index.js, I could not able to parse that. A bit guidance how to fixate index.js according to my database structure would be immensely appreciated. PS- I have never done coding in JS If you want more context, I'd be happy to provide it.

2 Answers 2

41

Change this:

exports.pushNotification = functions.database.ref('/messages').onWrite( event => {

const message = event.data.val();
const user = event.data.val();
});

to this:

exports.pushNotification = functions.database.ref('/messages').onWrite(( change,context) => {

const message = change.after.val();
});

Please check this:

https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database

The cloud functions were changed and now onWrite has two parameters change and context

The change has two properties before and after and each of these is a DataSnapshot with the methods listed here:

https://firebase.google.com/docs/reference/admin/node/admin.database.DataSnapshot

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Peter, I have been searching for this solution all day!
@PeterHaddad hey, I want to send the username with the body of notify and here is what it save in my DB like this imgur.com/65Z25Rh , and i save it a variable like this const userName = snapshot.after.val().username._55 but the logs tell me Cannot read property '_55' of undefined at exports.sendPushR.functions.database.ref.onWrite
-2
'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');
        });
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.