I develop in iOS and this is the first time I'm coding in Typescript. I made my first Cloud Function that triggers when a new chat message is sent in RTDB and notifies the members that receive the message.
When I make the call to Firestore to get tokens of the user devices (userTokens) I get no errors and have the correct path, but the data returned from those promises don't show anything. When I log the "tokenList" it just says ["0"]. I think the error is when I push the promise to a list or resolve them, but I haven't managed to fix it.
The code:
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}`)
})
})
})