0
votes

I have a 'Users' collection which contains a list of documents, each document has a user object and a sub-collection 'Notifications'. whenever a user get a new notification, a new document is created under it's sub-collection Notifications.

The trigger in the cloud function is not triggered.

Here is my Firestore structure:

Firestore structure

And here is my function:

let functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.firestore.collection('Users/{userID}/Notifications/{notificationId}')//
    .onWrite(async (change,context) => {

        // get receiver ID
        const receiverId = context.params.userID;

        // get notification object
        const notificationObject = change.after.val();
        // get sender ID
        const senderUid = notificationObject.senderId;

        console.log('sending notification to: ' + senderUid);

        if (senderUid === receiverId) {
            // this should never be called
            console.log('sender is the receiver.');
        }

        // receiver's token
        const getTokenPromise = await admin.firestore().collection('Users').doc(receiverId).once('value');
        const token = getTokenPromise.val().deviceToken;
        // sender user object
        const sender = await admin.firestore().collection('Users').doc(senderUid).once('value');

        const payload = {
            data: {
                senderName: sender.val().userName,
                senderPhoto: sender.val().userPhoto,
                object: JSON.stringify(notificationObject)
            }
        };

        try {
          const response = await admin.messaging().sendToDevice(token, payload);
          console.log("Successfully sent notification:", response);
        }
        catch (error) {
          console.log("Error sending notification:", error);
        }
    });

What I'm doing wrong ?

1
How do you verify it is not triggered? From the Cloud Functions log? I can see one potential problem (untested): You can no longer pass in functions.config().firebase when initializing. See firebase.google.com/docs/functions/…Renaud Tarnec
Thank you for your response Renaud, I changed the initialisation, but still not triggered. I'm verifying through the Logs, and I'm making a breakpoint on the client side (android) on the onMessageReceived method.Walid

1 Answers

3
votes

You should declare your function with

exports.sendNotification = functions.firestore.document('Users/{userID}/Notifications/{notificationId}')//
    .onWrite(async (change,context) => {...});

and not with

exports.sendNotification = functions.firestore.collection('Users/{userID}/Notifications/{notificationId}')//
    .onWrite(async (change,context) => {...});

As a matter of fact, Cloud Functions for Firestore are triggered at the level of the document. More details here and here in the doc.