0
votes

i'm using firebase cloud functions to listen to database value events , this is my code

    var functions = require('firebase-functions');
var firebase = require('firebase-admin');

var serviceAccount = require("./serviceAccountKey.json");

firebase.initializeApp({
    credential : firebase.credential.cert(serviceAccount),
    databaseURL: "https://*******.firebaseio.com"
});

exports.notifications = functions.database.ref('/chat/{senderID}/{destinationID}/messages/{pushID}')
    .onWrite(event => {        
        var eventSnapshot = event.data;        
        var sender = eventSnapshot.child('sender').val();
        var message = eventSnapshot.child('message').val();
        var destination = eventSnapshot.child('destination').val();        
        if (event.params.senderID === sender) 
            sendMessage(message,sender,destination);    
    }
);

function sendMessage(message, sender, destination) {

    var senderUser = firebase.database().ref('users/'+sender+'/name'); 
    var tokenUser = firebase.database().ref('fcm/'+destination+'/token');
        tokenUser.once('value').then(function(tokenSnapshot) {
            var token = tokenSnapshot.val(); 
                        console.log(token);                        

    }, function (errorObject) {
  console.log("The read failed: " + errorObject.code);
});     
}

onWrite function execute normally , but tokenUser.once() is not executed.

1
Is this true ? event.params.senderID === sender . Put a few log statements in there with what they output so we can at least know what's happening when you run it. - Ced
sendMessage function is executing i tested it wuth log , so the problem is with data retrieving function - Neo Algeria
Ìs there something in your DB at fcm/'+destination+'/token ? - Ced
yes it is a correct path - Neo Algeria
I do but if I remember correctly I had the issue where a null value just outputs a line break (instead of undefined or null). So you might want to double check that this is not happening with : console.log('my token is ', token); - Ced

1 Answers

0
votes

maybe if you try using tokenUser.once('value') and don't pass a function, and get directly the tokenSnapshot; something like this:

tokenUser.once('value').then(tokenSnapshot => {
        var token = tokenSnapshot.val(); 
        console.log(token);                        

});     

You can pass the function if you use tokenUser.once() with a callback; something like this:

tokenUser.once('value', function(tokenSnapshot) {
        var token = tokenSnapshot.val(); 
                    console.log(token);                        

}, function (errorObject) {
  console.log("The read failed: " + errorObject.code);
});