David Henry
David Henry

Reputation: 3046

Get Document in Firestore Cloud Function

I am creating a Firebase cloud function that messages a particular user when their rating has been updated (a trigger from Firestore).

So far I have;

// Send New Rating Notifications
exports.sendNewRatingNotification = functions.firestore.document('users/{userID}/ratings/{ratingID}').onWrite((context) => {

    // Get {userID} and field of fcmToken and set as below

    var fcmToken = fcmToken;
    var payload = {
        notification: {
            title: "You have recieved a new rating",
            body: "Your rating is now..."
        }
    }

    return admin.messaging().sendToDevice(fcmToken, payload).then(function(response) {
        console.log('Sent Message', response);
    })
    .catch(function(error) {
        console.log("Error Message", error);
    })
})

I need to access the {userID} documents' fcmToken field to use below how to I approach this from using the wildcard {userID}

Upvotes: 3

Views: 1725

Answers (3)

David Henry
David Henry

Reputation: 3046

I've implemented the process from the accepted answer above.

My Firebase Function is as follows;

exports.sendNewRatingNotification = functions.firestore.document('users/{userID}/ratings/{ratingID}').onWrite((change, context) => {
    var userRef = admin.firestore().collection('users').doc(context.params.userID);
    return userRef.get().then(doc => {
        if (!doc.exists) {
            console.log('No such document!');
        } else {
            const data = change.after.data();
            const fcmToken = doc.data().fcmToken;
            var payload = {
                notification: {
                    title: "New Rating",
                    body: "You have recieved a " + data["rating"] + "* rating"
                }
            }
            return admin.messaging().sendToDevice(fcmToken, payload).then(function(response) {
                console.log('Sent Message:', response);
            })
            .catch(function (error) {
                console.log('Error Message:', error);
            });
        };
    });
});

Upvotes: 2

Doug Stevenson
Doug Stevenson

Reputation: 317372

This is spelled out in the documentation for wildcards:

exports.sendNewRatingNotification =
functions.firestore.document('users/{userID}/ratings/{ratingID}').onWrite((change, context) => {
    const userID = context.params.userID
})

Note that the first argument to the callback is not context, it's Change object that describes the before and after state of the document. The second argument is a context that contains the parameters of the change.

Upvotes: 3

Pratik Butani
Pratik Butani

Reputation: 62411

If you check line number 30-31 of functions-samples/fcm-notifications repository.

You will get using:

  const userID= context.params.userID;

Hope it will helps you.

Thank you.

Upvotes: 1

Related Questions