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:
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 ?
functions.config().firebase
when initializing. See firebase.google.com/docs/functions/… – Renaud Tarnec