1
votes

I am sending a notification using a device token with Cloud Firestore and Cloud Function. Now the system will store the device token in which user logs in. Since a user may have multiple device or may logged in using different device, all I want is to send this notification to those device using the stored device token. This is how a users document looks like, I store the tokens as a nested object.

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

Now I want to iterate and get all key and value then send a notification to those device using the collected tokens. How am I going to perform this? Is this the best approach?

1
Do you want to send a notification to all this tokens(devices) when a certain event occurred using cloud functions right?Ahmed Abdelmeged
@AhmedAbd-Elmeged yesMihae Kheel
OK I will answer it using Typescript assuming its a firestore trigger is that will work with you?Ahmed Abdelmeged
I am using Javascipt, is it far different?Mihae Kheel
No very small different you can convert it pretty easyAhmed Abdelmeged

1 Answers

2
votes

OK here is a cloud function that will send a notification to all user devices when a firestore event triggered. Assuming you have the user id in that trigger from the event object or another way. The function will use that id to get the user document from the database depending on how you stored it then get the notification token and send it to all of his devices in the device_tokens map

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
        })
})