Firebase Cloud功能在实时数据库上获取数据


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

我无法在/用户/{uname}/token-> value中获得令牌。


错误:提供给sendTodeVice((的注册令牌(S(必须是非空字符串或非空数阵列。 在firebasemessagingerror.firebaseerror [作为构造函数](/srv/node_modules/firebase-admin/lib/lib/utils/error.js:42:28( 在firebasemessagingerror.prefixedfirebaseerror [作为构造函数](/srv/node_modules/firebase-admin/lib/lib/utils/error.js:88:28( 在New Firebasemessagingerror(/srv/node_modules/firebase-admin/lib/utils/error.js:253:16( 在Messing.validateregistrationTokenStype(/srv/node_modules/firebase-admin/lib/messaging/messaging/messaging.js:911:19( 在Mesgaging.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( 请访问/沃克/沃克。js:825:24 在 在process._tickdomaincallback(内部/process/next_tick.js:229:7(

您无法通过执行

获得数据库节点的值
let token = root.child('/users/' + uname + '/token').ref.token;

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

这意味着您必须按照以下方式修改代码:

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

相关内容

  • 没有找到相关文章

最新更新