javascript - 云 Firestore : Retrieve dynamic field keys with Javascript

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

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

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

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

最佳答案

好的,这是一个云函数,它会在触发 firestore 事件时向所有用户设备发送通知。假设您从事件对象或其他方式获得该触发器中的用户 ID。该函数将根据您的存储方式使用该 ID 从数据库中获取用户文档,然后获取通知 token 并将其发送到 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
        })
})

关于javascript - 云 Firestore : Retrieve dynamic field keys with Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53020593/

相关文章:

javascript - 如何在 bootstrap 3 中创建响应式/粘性页脚?

javascript - 无法更新 Mongoose 值

java - 使用 Dropbox API 共享文件夹时出现模式不匹配错误

flutter - 后台 FCM 触发时生成 Flutter 本地通知

javascript - 不是 css 中的选择器不起作用?

javascript - 在javascript计时器中更改字体颜色

android - 带有振动的不良加速度计数据

android - sendEmptyMessageAtTime 问题

ios - 使用未解析的标识符 'FIRApp'

android - 谷歌 GMS :play service conflict with firebase