Reputation: 1192
Is it possible to achieve something like this? P.s it's not working, I don't know why.
exports.Myfunc = functions.firestore.document('collection/{id}').onCreate(async (snapshot, context) => {
const Id =snapshot.data().id;
const Token=snapshot.data().deviceToken;
functions.firestore.document('collection2/Id').onUpdate(async (snapshot, context) => {
const data1=snapshot.data().data;
const data2=snapshot.data().data2;
var payload = {
notification: {
priority : "high",
title: 'Notification',
body: '<body>',
},
data: {
"click_action": "FLUTTER_NOTIFICATION_CLICK",
'data1':data1,
'data2':data2,
},
};
try {
const response = await admin.messaging().sendToDevice(Token, payload);
console.log('Notification sent successfully');
} catch (err) {
console.log(err);
}
});
});
What i'm trying to do is, listening to document creation in a collection, and when created, then listening to updates in a particular document(whose id is given by the previous listener), and when, this document UPDATES, then sending a notification to the device token given by the previous listener.
How can I achieve this? Is there any other possible way of doing this,or something i need to keep in mind?
Please help.
Upvotes: 1
Views: 339
Reputation: 83058
You cannot define a Cloud Function within a Cloud Function.
If I correctly understand what you want to achieve, you could do as follows:
Create a Cloud Function for Firestore that is triggered with onUpdate()
in order to listen to changes to the documents of collection2
. Similarly to what you did in your code:
exports.Myfunc = functions.firestore.document('collection2/Id')
.onUpdate(async (change, context) => {
// ...
const docId = context.params.Id;
// ...
});
In this Cloud Function, verify if the document Id (context.params.Id
) is within a list of Ids that you have saved somewhere in the Firestore database. E.g. as an Array in a specific doc (mind the maximum 1 MiB size for a document) or within dedicated docs in a specific collection.
If the Id is within the list, send the message.
You would populate this list of Ids, either from your Flutter app, when you create the document collection/{id}
, or, if necessary (e.g. you want to restrict the read/write access to the list of Ids), via another Cloud Function.
PS: Note that in a Cloud Function that is triggered with onUpdate()
, you should not do
exports.Myfunc = functions.firestore.document('collection2/Id').onUpdate(async (snapshot, context) => {
//...
const data1 = snapshot.data(); // <= this will not work
//...
});
See the doc for more details.
Upvotes: 3