Firebase Cloud Functions在Create

时间:2019-05-07 12:39:30

标签: node.js firebase-realtime-database firebase-cloud-messaging google-cloud-functions

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: 'Seda Güler'

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


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

我无法在/ users / {uname} / token->值上获得令牌。


错误:提供给sendToDevice()的注册令牌必须是非空字符串或非空数组。     在FirebaseMessagingError.FirebaseError [作为构造函数](/srv/node_modules/firebase-admin/lib/utils/error.js:42:28)     在FirebaseMessagingError.PrefixedFirebaseError [作为构造函数](/srv/node_modules/firebase-admin/lib/utils/error.js:88:28)     在新的FirebaseMessagingError(/srv/node_modules/firebase-admin/lib/utils/error.js:253:16)     在Messaging.validateRegistrationTokensType(/srv/node_modules/firebase-admin/lib/messaging/messaging.js:911:19)     在Messaging.sendToDevice(/srv/node_modules/firebase-admin/lib/messaging/messaging.js:532:14)     在exports.sendNotification.functions.database.ref.onCreate(/srv/index.js:28:5)     在cloudFunctionNewSignature(/srv/node_modules/firebase-functions/lib/cloud-functions.js:120:23)     在/worker/worker.js:825:24     在     在process._tickDomainCallback(internal / process / next_tick.js:229:7)

1 个答案:

答案 0 :(得分:1)

您不能通过这样做获得数据库节点的值

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

您需要使用once()Reference方法查询数据库,该方法是异步的。

这意味着您必须按以下步骤修改代码:

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: 'Seda Güler    
         })
       }
     };

     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);
     }); 
});