Automatically generating cloud functions when group created - node.js

What is the best approach for my case? A user creates a messaging group in my app. Then the group will get its own auto id.
Now I want to use cloud func from firebase to check for new messages and to do a push notification.
The code below checks if a group is created and send the push notification. But this only works when I know the generated auto id and post it manually in the code below. How can I solve this issue? Should my App create for each group its own cloud function? Would this not be too much? Or can I use somehow a wildcard?
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.Push = functions.database.ref('/placeID/theGeneratedIdComesHere/{messageID}/')
.onCreate((snapshot, context) => {
var nameUser = String(snapshot.val().userName)
var textUser = String(snapshot.val().userComment)
var topic = 'weather';
const payload = {
notification: {
title: nameUser,
body: textUser,
badge: '1',
sound: 'default'
}
};
admin.messaging().sendToTopic(topic,payload);
})

You can make the group ID a parameter on your Cloud Function declaration:
exports.Push = functions.database.ref('/placeID/{groupID}/{messageID}/')
Then you can access that group ID in your functions code with:
const groupID = context.params.groupID;
And then you can use that value in your code to make it to what this specific group needs.

Related

how to write function for a specific document in firestore?

below is the function, i have used from youtube .
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.androidPushNotification =
functions.firestore.document('MyMoneyNotifications/{MyPercentageMoney}').onCreate(
(snapshot, context)=>
{
admin.messaging().sendToTopic(
"new_user_forums",
{
notification:{
title:snapshot.data().title,
body: snapshot.data().body
}
});});
it is working fine.
but i want to check for below structure.
Notifications(collection)
->UserId(document)
->MyNotification(collection)
->notify1
->notify2
now, i want to check for a specific user if he had any new notifications. how to check for the collection "MyNotification" in firebase functions
If you are trying to listen to sub-collections then you can set the path to:
exports.androidPushNotification =
functions.firestore.document('Notifications/{userId}/MyNotification/{notificationId}')
You can read more about this in the documentation

Firebase functions multi child change

hi firebase functions I want to change multiple children, but cannot change all children under user id. can you help me with this topic
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var database = admin.database();
exports.newNodeDetected = functions.database.ref('system/{userId}/value')
.onWrite((Change) =>{
var oldDeger = Change.before.val();
var newDeger = Change.after.val();
if (newDeger === '0'){
database.ref(`system/${userId}/value`).set('1');
}
})
enter image description here
You can update multiple children in several ways using standard object manipulation and direct writes as demonstrated in your question.
You may be interested in using update rather than set when updating multiple fields.
You will also notice I added a Context field which allows you to access information such as the userID from the reference path and other information: Source
exports.newNodeDetected = functions.database.ref('system/{userId}/value')
.onWrite((Change, Context) =>{
var oldDeger = Change.before.val();
var newDeger = Change.after.val();
if (newDeger === '0'){
database.ref(`system/${Context.params.userId}/value`).set('1');
database.ref(`system/${Context.params.userId}/otherField`).update({another:field});
}
})
Resource: Medium Article: Realtime Set Vs Update

Sending Notification With Firebase Cloud Functions to Specific users

I am using firebase cloud function in my firebase group chat app, Setup is already done but problem is when some one send message in any group then all user get notification for that message including non members of group.
I want to send notification to group specific users only, below is my code for firebase cloud function -
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const _ = require('lodash');
admin.initializeApp(functions.config().firebase);
exports.sendNewMessageNotification = functions.database.ref('/{pushId}').onWrite(event => {
const getValuePromise = admin.database()
.ref('messages')
.orderByKey()
.limitToLast(1)
.once('value');
return getValuePromise.then(snapshot => {
const { text, author } = _.values(snapshot.val())[0];
const payload = {
notification: {
title: text,
body: author,
icon: ''
}
};
return admin.messaging()
.sendToTopic('my-groupchat', payload);
});
});
This will be really help full, if anyway some one can suggest on this.
As per our conversation on the comments I believe that the issue is that you are using a topic that contains all the users, which is the my-groupchat topic. The solution would be to create a new topic with the users that are part of this subtopic.
As for how to create such topics, there are a couple of examples in this documentation, in there you can see that you could do it server side, or client side. In your case, you could follow the examples for the server side, since you would need to add them in bulk, but as new users are added it could be interesting to implement the client side approach.

Using wildcards in firestore get query

I want to create a cloud function in firebase that gets triggered whenever a user logs in for the first time. The function needs to add the UID from the authentication of the specific user to a specific, already existing document in firestore. The problem is that the UID needs to be added to a document of which I do not know the location. The code I have right now doesn't completely do that, but this is the part where it goes wrong. The database looks like this when simplified
organisations
[randomly generated id]
people
[randomly generated id] (in here, a specific document needs to be found based on known email
adress)
There are multiple different organisations and it is unknown to which organisation the user belongs. I thought of using a wildcard, something like the following:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
console.log('function ready');
//Detect first login from user
//if(firebase.auth.UserCredential.isNewUser()){
if(true){
//User is logged in for the first time
//const userID = firebase.auth().currentUser.UID;
//const userEmail = firebase.auth().currentUser.email;
const userID = '1234567890';
const userEmail = 'example#example.com';
//Get email, either personal or work
console.log('Taking a snapshot...');
const snapshot = db.collection('organisations/{orgID}/people').get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.data());
});
});
}
I commented out some authentication-based lines for testing purposes. I know the code still runs, because hardcoding the orgID does return the right values. Also, looping trough every organisation is not an option, because I need to have the possibility of having a lot of organisations.
A lot of solutions are based on firestore triggers, like onWrite, where you can use wildcards like this.
However, I don't think that's possible in this case
The solution to the problem above:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
//Add UID to document in DB[FMIS-94]
//Detect first login from user
//if(firebase.auth.UserCredential.isNewUser()){
if(true){
//User is logged in for the first time
//const userID = firebase.auth().currentUser.UID;
//const userEmail = firebase.auth().currentUser.email;
const userID = '1234567890';
const userEmail = 'example#example.com';
var docFound = false;
//Get email, either personal or work
console.log('Taking a snapshot...');
//Test for work email
const snapshot = db.collectionGroup('people').where('email.work', '==', userEmail).get()
.then(function(querySnapshot){
querySnapshot.forEach(function(doc){
//work email found
console.log('work email found');
console.log(doc.data());
docFound = true;
const organisationID = doc.ref.parent.parent.id;
writeUID(doc.id, userID, organisationID);
});
});
if(!docFound){
//Test for personal email
const snapshot = db.collectionGroup('people').where('email.personal', '==', userEmail).get()
.then(function(querySnapshot){
querySnapshot.forEach(function(doc){
//personal email found
console.log('personal email found');
console.log(doc.data());
const organisationID = doc.ref.parent.parent.id;
writeUID(doc.id, userID, organisationID);
});
});
}
}
async function writeUID(doc, uid, organisationID){
const res = db.collection(`organisations/${organisationID}/people`).doc(doc).set({
userId: uid
}, { merge: true });
}
This was exactly what I needed, thanks for all your help everyone!
It is not possible to trigger a Cloud Function when a user logs in to your frontend application. There is no such trigger among the Firebase Authentication triggers.
If you want to update a document based on some characteristics of the user (uid or email), you can do that from the app, after the user has logged in.
You mention, in your question, "in here, a specific document needs to be found based on known email address". You should first build a query to find this document and then update it, all of that from the app.
Another classical approach is to create, for each user, a specific document which uses the user uid as document ID, for example in a users collection. It is then very easy to identify/find this document, since, as soon the user is logged in you know his uid.
I'm not sure I understand you correctly, but if you want to search across all people collections not matter what organizations document they're under, the solution is to use a collection group query for that.
db.collectionGroup('people').get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log("user: "+doc.id+" in organization: "+doc.ref.parent.parent.id);
});
});
This will return a snapshot across all people collections in your entire Firestore database.
First setup Cloud Functions according to the official Documentation.
Then after setting up create functions like this:
exports.YOURFUNCTIONNAME= functions.firestore
.document('organisations/[randomly generated id]/people/[randomly generated id]')
.oncreate(res => {
const data = res.data();
const email = data.email;/----Your field name goes here-----/
/-----------------Then apply your logic here---------/
)}
This will triggers the function whenever you create the People -> Random ID

Saving to two different Firestore databases with dialogflow

I'm making an actions on google project that will require adding data to two different Cloud Firestore. For some reason when I trigger the intent, it will only save to the original Cloud Firestore, but not the new one.
For simplicity, I'm going to refer to the original Cloud Firestore as "DB1" and the new one/ second one as "DB2"
Here's what I had tried:
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
const {google} = require('googleapis');
const {
<Basically All of the libraries / AOG functions>
} = require('actions-on-google');
const defaultAppConfig = {"<FIREBASE CREDENTIALS FOR DB1 >"}
const OtherAppConfig = {"<FIREBASE CREDENTIALS FOR DB2>"}
const defaultApp = admin.initializeApp(defaultAppConfig); // DB1
const otherApp = admin.initializeApp(OtherappConfig, 'Other'); // DB2
const db = admin.firestore(functions.config(defaultApp).firebase); //DB1
const ab = admin.firestore(functions.config(otherApp).firebase); // DB2
const app = dialogflow({
debug: true,
clientId: '<DIALOGFLOW CREDENTIALS>'
});
app.intent('DB2 Write', (conv) =>{
conv.ask('Okay I made the write to DB2');
var data = {
name: 'This is a Test write'
};
var setDoc = ab.collection('Test').doc('Write').set(data);
});
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);
Sorry if some parts are unnecessary, I wanted to include as much information as I could (I might be missing something that someone else sees).
To sum up what I thought would happen, I thought when I triggered the intent 'DB2 Write' that it would write 'This is a Test Write' to DB2, however it just keeps writing the message/data to DB1.
How do I get this working so it will write to my second Cloud Firestore or "DB2" when this intent is triggered?
Thanks for the help!
Note: If it makes a difference, I'm using the dialogflow inline editor for this code.
____________________________________________________________________________
Update: Here is what I have tried/ updated and it still writes to DB1
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
const otherAdmin = require('firebase-admin');
otherAdmin.initializeApp({
credential: otherAdmin.credential.cert(OtherAppConfig)
},'Other');
const ab = otherAdmin.firestore();
and as well:
admin.initializeApp(defaultAppConfig);
var otherApp = admin.initializeApp(OtherAppConfig, 'other');
console.log(admin.app().name); // '[DEFAULT]'
console.log(otherApp.name); // 'other'
// Use the shorthand notation to retrieve the default app's services
var db = admin.firestore(functions.config().firebase);
// Use the otherApp variable to retrieve the other app's services
var ab = otherApp.firestore(functions.config().firebase);
I'd like to note, the credentials I'm using for "OtherAppConfig" and "defaultAppConfig" were taken from the Firebase private key. ie: firebase console > project overview > service accounts > generate private key. Could this be the problem?
I think the problem is thus:
A Dialogflow project and a Firebase project are the same under the hood. This cool, as your Firebase Functions will know intuitively connect with Dialogflow and your database without a lot of manual configuration.
However, if you have two databases from different Cloud Projects, you will need to do some additional configurations to connect securely. I'm not sure what your AppConfigs contain, but they may not be sufficiently setup. As such, the Firebase setup may be pulling the default (current project) app and database when you're grabbing the functions config.
You may want to, for your second project, download the service key. Then you can load it as a file or directly as JSON in your startup routine.
This snippet below should work the way you want.
// Setup 1st db, this project's db
const admin = require('firebase-admin');
admin.initializeApp(); // Initialize with default params as we get it by default
const db = admin.firestore();
// Setup 2nd db
const otherAdmin = require('firebase-admin'); // We can import twice
const myOtherServiceKey = { ... }
otherAdmin.initializeApp({
credential: otherAdmin.credential.cert(myOtherServiceKey)
});
const ab = otherAdmin.firestore(); // This should be the DB of our second project

Resources