【问题标题】:Cloud Firestore: Retrieve dynamic field keys with JavascriptCloud Firestore:使用 Javascript 检索动态字段键
【发布时间】:2019-03-31 21:57:12
【问题描述】:

我正在使用带有 Cloud Firestore 和 Cloud Function 的设备令牌发送通知。现在系统将存储用户登录的设备令牌。由于用户可能有多个设备或可能使用不同的设备登录,我只想使用存储的设备令牌将此通知发送到这些设备。这是用户文档的样子,我将标记存储为嵌套对象。

{
name: "Frank Kemerut",
device_tokens: { 23qweq: "LG G6", Os23pk: "Samsung S6", asd231: "Samsung S9" },
age: 12
}

现在我想迭代并获取所有键和值,然后使用收集的令牌向这些设备发送通知。我将如何执行此操作?这是最好的方法吗?

【问题讨论】:

  • 当某个事件发生时,您想使用云功能向所有这些令牌(设备)发送通知吗?
  • @AhmedAbd-Elmeged 是的
  • 好的,假设它的 Firestore 触发器适用于您,我将使用 Typescript 回答它?
  • 我用的是Javascipt,差别大吗?
  • 没有很小的不同,你可以很容易地转换它

标签: javascript android firebase-cloud-messaging google-cloud-firestore google-cloud-functions


【解决方案1】:

好的,这是一个云功能,它会在触发 Firestore 事件时向所有用户设备发送通知。假设您从事件对象或其他方式获得该触发器中的用户 ID。该函数将使用该 id 从数据库中获取用户文档,具体取决于您的存储方式,然后获取通知令牌并将其发送到 device_tokens 映射中的所有设备

export const sendEventNotification = functions.firestore.document('events/${eventId}')
    .onCreate((data, context) => {
        const userId = "someId"
        //Get the user document to get the notification tokens.
        return firestore.doc(`users/${userId}`).get().then((user) => {

            //dummy notification payload
            const payload = {
                data: {
                    event: JSON.stringify(data.data())
                }
            }

            //The device tokens mapped to device name.
            const device_tokens = user.data().device_tokens

            //Array of notification tokens that we will send a notification to.
            const promises = []
            Object.keys(device_tokens).forEach(token => {
                promises.push(admin.messaging().sendToDevice(token, payload))
            })

            return Promise.all(promises)
        }).catch((error) => {
            console.log(`Failed to send user notification. Error: ${error}`)
            return null
        })
})

【讨论】:

  • 我可以在不做承诺的情况下直接将管理消息放入 foreach 循环中吗?
  • 不,你需要添加 Promise,因为它是一个异步函数
  • 好的,谢谢,我现在就试试,如果可行,我会立即接受这个答案。
  • 如果 device_tokens 为空怎么办?
  • 是的,你应该在调用promise.push之前检查key是否为空,我忘记添加了。如果解决方案适合您,请接受问题:)
猜你喜欢
  • 2018-04-27
  • 1970-01-01
  • 2018-05-07
  • 1970-01-01
  • 1970-01-01
  • 2018-05-27
  • 2023-03-09
  • 2018-03-26
  • 2018-10-15
相关资源
最近更新 更多