首页 > 解决方案 > 您如何获得服务器上所有令牌的值?

问题描述

我想从我的 Firebase 数据库中的这条路径收集我所有的 FCM 用户 iOS 设备令牌:

BootCamp/Notifications/iOS

在此位置,将创建一个 autoIDChild 以将用户的设备令牌存储为"deviceToken"

我一直在尝试遵循此链接上的 cloud_functions 示例,但由于我的用例不同,因此很难弄清楚。这是我在 JS 中的云功能代码:

exports.iOSPush = functions.database.ref('/BootCamp/Bulletins/date').onWrite((snapShot, context) =>{

let tokensSnapShot
let tokens

//here, I attempt to get access to all iOS tokens on my server
const getTokens = admin.database().ref('/BootCamp/Notifications/iOS/{key}').once('value');

return Promise.all([getTokens]).then( (results) => {
tokensSnapShot = results[0]
tokens = Object.keys(tokensSnapShot)

const payload = {
  notification:{
    title: 'congrats it works',
    body: 'Cloud function noti for ios',
    sound: 'default',
    badge: '1'
    }
};
  //tokens value in the console log is: "node_,ref_,index_". I was expecting an array of tokens:/
  return  admin.messaging().sendToDevice(tokens, payload)  
})
});

如何在我的服务器上获取这些 iOS 令牌?

标签: firebasepush-notificationfirebase-cloud-messaginggoogle-cloud-functionsremote-notifications

解决方案


请检查这个例子:

  return Promise.all([admin.database().ref(`/users/${user}/account/tokensArray`).once('value')]).then(results => {
    const tokens = results[0];
    if (!tokens.hasChildren()) return null;
    let payload = {
      notification: {
        title: 'title',
        body: 'message',
        icon: 'icon-192x192.png'
      }
    };
    const tokensList = Object.keys(tokens.val());
    return admin.messaging().sendToDevice(tokensList, payload);
  });

推荐阅读