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

exports.sendNotification = functions.database.ref('/messages/diyetisyen/{uname}/{msgid}/message')
.onCreate((snapshot, context) => {

let message = snapshot.val();
let uname = context.params.uname;
let root = snapshot.ref.root;
let token = root.child('/users/' + uname + '/token').ref.token;

let payload = {
  data: {
    custom_notification: JSON.stringify({
      body: message + '',
      title: 'aaaa'

    })
  }
};
let options = { priority: "high" };


return admin
  .messaging()
  .sendToDevice(token, payload, options);
  });

i cant get token on /users/{uname}/token -> value.


Error: Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array. at FirebaseMessagingError.FirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:42:28) at FirebaseMessagingError.PrefixedFirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:88:28) at new FirebaseMessagingError (/srv/node_modules/firebase-admin/lib/utils/error.js:253:16) at Messaging.validateRegistrationTokensType (/srv/node_modules/firebase-admin/lib/messaging/messaging.js:911:19) at Messaging.sendToDevice (/srv/node_modules/firebase-admin/lib/messaging/messaging.js:532:14) at exports.sendNotification.functions.database.ref.onCreate (/srv/index.js:28:5) at cloudFunctionNewSignature (/srv/node_modules/firebase-functions/lib/cloud-functions.js:120:23) at /worker/worker.js:825:24 at at process._tickDomainCallback (internal/process/next_tick.js:229:7)

1

1 Answers

1
votes

You cannot get the value of a database node by doing

let token = root.child('/users/' + uname + '/token').ref.token;

You need to query the database with the once() method of the Reference, which is asynchronous.

It means that you have to modify your code as follows:

exports.sendNotification = functions.database.ref('/messages/diyetisyen/{uname}/{msgid}/message')
.onCreate((snapshot, context) => {

    let message = snapshot.val();
    let uname = context.params.uname;
    let root = snapshot.ref.root;
    let tokenRef = root.child('/users/' + uname + '/token').ref;

    let payload = {
       data: {
         custom_notification: JSON.stringify({
           body: message + '',
           title: 'aaaa'   
         })
       }
     };

     let options = { priority: "high" };

     return tokenRef.once('value')
     .then(dataSnapshot => {
       const data = dataSnapshot.val();
       const token = data.token;   //Here I make the assumption the token is at '/users/' + uname + '/token/token'. You may adapt it as required

       return admin
       .messaging()
       .sendToDevice(token, payload, options);
     }); 
});