繁体   English   中英

Firebase 云函数中的聊天消息通知。 触发云时无法从 promise 获取数据 Function

[英]Chat message notification in Firebase Cloud Functions. Can't get data from a promise when triggering a Cloud Function

我在 iOS 开发,这是我第一次在 Typescript 编码。我制作了我的第一个 Cloud Function,它在 RTDB 中发送新聊天消息时触发并通知接收消息的成员。

当我调用 Firestore 以获取用户设备的令牌 (userTokens) 时,我没有收到任何错误并且路径正确,但是从这些承诺返回的数据没有显示任何内容。 当我记录“tokenList”时,它只是说 [“0”]。 我认为错误是当我将 promise 推送到列表或解决它们时,但我还没有设法修复它。

代码:

import * as functions from "firebase-functions"
import * as admin from "firebase-admin"
admin.initializeApp()

export const newLastMessageDetected = functions.database
.ref('/ChatMessages/{chatID}/{messageID}/')
.onCreate(async (snap, context) => {
    const values = snap.val()
    const chatID = context.params.chatID
    const messageID = context.params.messageID
    const message = values.message
    const fromID = values.fromID
    const fromName = values.fromName

    console.log( `LastMessage changed with chatID: ${chatID} and messageID ${messageID} `)
    console.log( `Last message: ${message} by fromID: ${fromID} and by name ${fromName}`)

    const payload = { 
        notification: {
            title: fromName,
            body: message
            
        }
    }

    let membersSnapshotRef =  admin.database().ref('/Members/' + chatID + '/')

    return membersSnapshotRef.once('value')
        .then(dataSnapshot => {
            const promises = []
            console.log('*** GOT SNAPSHOT ***')
            dataSnapshot.forEach((element) => {
                if (element.key != fromID && element.val() === true) {
                    const p = admin.firestore().collection('userTokens').doc(`${element.key}`).collection('devices').get()
                    console.log('*** GOT PROMISE ***')
                    console.log(`*** The recipientID: ${element.key} ***`)
                    console.log(`${p}`)                    
                    promises.push(p)
                }
                
            })
            return Promise.all(promises).then(snapshot => {
                console.log('*** GOT RETURNED PROMISES ***')
                const tokenList = []
                const data = snapshot.keys()
                for (const token in data) {
                    console.log(`${token}`)
                    tokenList.push(token)
                }
                console.log(`${tokenList}`)
                return admin.messaging().sendToDevice(tokenList, payload).then(result => {
                    console.log("Notification sent!");
                    return null;
            })

           
        })
        .catch(error => {
            console.log(`${error}`)
        })
       
    })
    
})

当您使用Promise.all()时,它返回的 promise 的结果始终是一个数组。

Promise.all(promises).then(snapshot => {
    // snapshot is an array of results with one element for each of the promises
})

您需要迭代该数组以找到存储在promises数组中的所有 promise 的结果。 snapshot.keys()不会迭代该数组 - 它只是为您提供一个数字列表,这些数字是这些数组的索引。 尝试改用snapshot.forEach()

您可能想要查看promise.all 的一些文档

我真的搞砸了,因为我试图检索查询中的数据; 没有意识到第一个循环是针对检索到的查询,所以我不得不对检索到的文档执行另一个循环。 设备令牌是每个文档 ID,其中时间戳存储为数据。

工作代码:

import * as functions from "firebase-functions"
import * as admin from "firebase-admin"
admin.initializeApp()

export const newLastMessageDetected = functions.database
.ref('/ChatMessages/{chatID}/{messageID}/')
.onCreate(async (snap, context) => {
    const values = snap.val()
    const chatID = context.params.chatID
    const messageID = context.params.messageID
    const message = values.message
    const fromID = values.fromID
    const fromName = values.fromName

    console.log( `LastMessage changed with chatID: ${chatID} and messageID ${messageID} `)
    console.log( `Last message: ${message} by fromID: ${fromID} and by name ${fromName}`)

    const payload = { 
        notification: {
            title: fromName,
            body: message
            
        }
    }

    let membersSnapshotRef =  admin.database().ref('/Members/' + chatID + '/')

    return membersSnapshotRef.once('value')
        .then(dataSnapshot => {
            const promises = []
            // const docIDS = []
            console.log('*** GOT SNAPSHOT ***')

            dataSnapshot.forEach((element) => {
                if (element.key != fromID && element.val() === true) {
                    const doc = admin.firestore().collection('userTokens').doc(`${element.key}`).collection('devices')
                    const p = doc.get()
                    // const docID = doc.id
                    console.log('*** GOT PROMISE ***')
                    console.log(`*** The recipientID: ${element.key} ***`)
                    // console.log(`*** The docID: ${docID} ***`)
                    promises.push(p)
                    // docIDS.push(docID)
                }
                
            })
            return Promise.all(promises)
        })
        .then(async querySnapshot => {
            console.log('*** GOT RETURNED PROMISES ***')
            const tokenList = []
            
            querySnapshot.forEach(snap => { // first here
                console.log(`${snap.id}  *** `) 
                console.log(`${snap}  *** `) 
                
                snap.forEach(doc => { // then here
                    console.log(`${doc.id}`)
                    tokenList.push(doc.id)
                })
            
            })

            await admin.messaging().sendToDevice(tokenList, payload)
            console.log("Notification sent!")
            return null
           
          
        })
        .catch(error => {
            console.log(`${error}`)
        })
    
})

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM