简体   繁体   English

Firebase Cloud Function错误:提供给sendToDevice()的注册令牌必须是非空字符串或非空数组

[英]Firebase Cloud Function error: Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array

I want to send a notification to all users who are confirmed guests when the object confirmedGuests is created in the Firebase Realtime Database. 我想在Firebase实时数据库中创建对象confirmGuest时向所有确认来宾的用户发送通知。

So, I first create an array of all the users from confirmedGuests object. 所以,我首先从confirmedGuests对象创建一个包含所有用户的数组。 Then, I iterate through all these users and push their deviceTokens to an array of deviceTokens. 然后,我遍历所有这些用户并将他们的deviceTokens推送到deviceTokens数组。 The array allDeviceTokens is expected to be the array of device tokens of all users in confirmedGuests. 数组allDeviceTokens应该是confirmGuests中所有用户的设备令牌数组。

However, when confirmedGuests object is created, the function returns an error. 但是,当创建confirmGuests对象时,该函数返回错误。

Below is my cloud function 下面是我的云功能


    exports.sendNotification = functions.database
    .ref('/feed/{pushId}/confirmedGuests')
    .onCreate((snapshot, context) => {
        const pushId = context.params.pushId;
        if (!pushId) {
            return console.log('missing mandatory params for sending push.')
        }
        let allDeviceTokens = []
        let guestIds = []
        const payload = {
            notification: {
                title: 'Your request has been confirmed!',
                body: `Tap to open`
            },
            data: {
                taskId: pushId,
                notifType: 'OPEN_DETAILS', // To tell the app what kind of notification this is.
            }
        };
          let confGuestsData = snapshot.val();
          let confGuestItems = Object.keys(confGuestsData).map(function(key) {
              return confGuestsData[key];
          });
          confGuestItems.map(guest => {
            guestIds.push(guest.id)
          })
          for(let i=0; i<guestIds.length; i++){
            let userId = guestIds[i]
            admin.database().ref(`/users/${userId}/deviceTokens`).once('value', (tokenSnapshot) => {
              let userData = tokenSnapshot.val();
              let userItem = Object.keys(userData).map(function(key) {
                  return userData[key];
              });
              userItem.map(item => allDeviceTokens.push(item))
            })
          }
          return admin.messaging().sendToDevice(allDeviceTokens, payload);
    });

You're loading each user's device tokens from the realtime database with: 您正在从实时数据库加载每个用户的设备令牌:

admin.database().ref(`/users/${userId}/deviceTokens`).once('value', (tokenSnapshot) => {

This load operation happens asynchronously. 此加载操作异步发生。 This means that by the time the admin.messaging().sendToDevice(allDeviceTokens, payload) calls runs, the tokens haven't been loaded yet. 这意味着,当admin.messaging().sendToDevice(allDeviceTokens, payload)调用运行时,尚未加载令牌。

To fix this you'll need to wait until all tokens have loaded, before calling sendToDevice() . 要解决此问题,您需要等到所有令牌都已加载,然后再调用sendToDevice() The common approach for this is to use Promise.all() 常见的方法是使用Promise.all()

let promises = [];
for(let i=0; i<guestIds.length; i++){
  let userId = guestIds[i]
  let promise = admin.database().ref(`/users/${userId}/deviceTokens`).once('value', (tokenSnapshot) => {
    let userData = tokenSnapshot.val();
    let userItem = Object.keys(userData).map(function(key) {
      return userData[key];
    });
    userItem.map(item => allDeviceTokens.push(item))
    return true;
  })
  promises.push(promise);
}
return Promise.all(promises).then(() => {
  return admin.messaging().sendToDevice(allDeviceTokens, payload);
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Firebase错误:提供给sendToDevice()的注册令牌必须是非空字符串或非空数组 - Firebase Error: Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array ESLint 7.1.0 错误:“模式”必须是非空字符串或非空字符串数组 - ESLint 7.1.0 Error: 'patterns' must be a non-empty string or an array of non-empty strings 错误:“输入”过滤器需要非空数组 - Error: A non-empty array is required for 'in' filters 如何修复“未知错误状态:错误:uid必须是一个非空字符串,最多128个字符。”在Firebase函数中 - How To Fix “Unknown error status: Error: The uid must be a non-empty string with at most 128 characters.” in Firebase Functions 消息内容必须是非空字符串 MessageEmbed - Message Content Must Be A Non-Empty String MessageEmbed 错误:消息内容必须是非空字符串。 || if (typeof data;== 'string') throw new error(errorMessage); - Error: Message content must be a non-empty string. || if (typeof data !== 'string') throw new error(errorMessage); 如果它是第一个非空数组,则返回true - Return true if it's first non-empty array JS:仅针对非空和字符串值类型过滤数组 - JS: Filter array only for non-empty and type of string values 错误:RangeError [MESSAGE_CONTENT_TYPE]:消息内容必须是非空字符串 - Error : RangeError [MESSAGE_CONTENT_TYPE]: Message content must be a non-empty string 未捕获(承诺)错误:“args.method”必须是非空字符串 - Uncaught (in promise) Error: 'args.method' must be a non-empty string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM