I want to send the user a push notification with cloud functions on Firebase if someone commented to a topic on his iOS Device.
This code below works fine if I put the content of the notification manually.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.Push = functions.database.ref('/placeID/{pushId}/')
.onCreate((snapshot, context) => {
var topic = 'weather';
const payload = {
notification: {
title: 'User Max',
body: 'Hi how are you?',
badge: '1',
sound: 'default'
}
};
admin.messaging().sendToTopic(topic,payload);
})
In the next step I want to get the content of the comment the person has sent. Kinda get the value of the snapshot.
I tried it like this and get no error in the Logs Explorer from Google. But also no Push Notification anymore.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.Push = functions.database.ref('/placeID/{autogeneratedplaceID}/')
.onCreate((snapshot, context) => {
var username = snapshot.child("userName").val()
var usercomment = snapshot.child("userComment").val()
var topic = 'weather';
const payload = {
notification: {
title: username,
body: usercomment,
badge: '1',
sound: 'default'
}
};
admin.messaging().sendToTopic(topic,payload);
})
What is wrong here? I also found a video on Youtube with the exact solution. But this is for android and it did not really help me. Youtube
This is how my firebase realtime database structure looks like.
Related
Just starting to use Firebase functions and have the sample working, but confused because the update event doesn't occur if I change the 'messages' collection to a different name, eg 'listings'. I change the word 'messages' in two places, on the 'add' and the 'makeUppercase' line. I get the response OK, it writes the data to the collection, but doesn't fire the event. Must be simple, but can't google it.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.addMessage = functions.https.onRequest(async (req, res) => {
// Grab the location parameter.
const inputcode = req.query.code || 'blank';
// Push the new message into Cloud Firestore using the Firebase Admin SDK.
const writeResult = await admin.firestore().collection('messages').add({inputcode: inputcode});
// Send back a message that we've succesfully written the message
res.json({result: `Message with ID: ${writeResult.id} added.`});
});
exports.makeUppercase = functions.firestore.document('/messages/{documentId}')
.onCreate((snap, context) => {
// Grab the current value of what was written to Cloud Firestore.
const inputcode = snap.data().inputcode;
// Access the parameter `{documentId}` with `context.params`
functions.logger.log('Uppercasing', context.params.documentId, inputcode);
const areacode = inputcode.toUpperCase();
const written = new Date();
return snap.ref.set({written, areacode}, {merge: true});
});
I'm using the local firebase emulator to do this test, by the way.
This is the new version, ony changing 'messages' to 'vvvv' in two places.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.addMessage = functions.https.onRequest(async (req, res) => {
// Grab the location parameter.
const inputcode = req.query.code || 'blank';
// Push the new message into Cloud Firestore using the Firebase Admin SDK.
const writeResult = await admin.firestore().collection('vvvvv').add({inputcode: inputcode});
// Send back a message that we've succesfully written the message
res.json({result: `Message with ID: ${writeResult.id} added.`});
});
exports.makeUppercase = functions.firestore.document('/vvvvv/{documentId}')
.onCreate((snap, context) => {
// Grab the current value of what was written to Cloud Firestore.
const inputcode = snap.data().inputcode;
// Access the parameter `{documentId}` with `context.params`
functions.logger.log('Uppercasing', context.params.documentId, inputcode);
const areacode = inputcode.toUpperCase();
const written = new Date();
return snap.ref.set({written, areacode}, {merge: true});
});
OK. Doug, your suggestion sank in after an hour or so! I've restarted everything and think that I understand. If I change the name in those two places, without restarting, the collection.add function takes place and I can see the record in the new collection, but the onCreate event didn't fire. I had to restart the whole service to restart buth parts. I was getting confused because one part was working and not the other. Thanks for your patience.
I build an app which i need to add in it many types of notifications but i can't do it with myself because am have tiny knowledge about JS
I tried to deploy many functions by differnt body , title ..etc but it seems not able to deploy many functions in Firebase Functions
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/Noti/{receiver_user_id}/{notification_id}')
.onWrite((data, context) =>
{
const receiver_user_id = context.params.receiver_user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification to send to :' , receiver_user_id);
if (!data.after.val())
{
console.log('A notification has been deleted :' , notification_id);
return null;
}
const DeviceToken = admin.database().ref(`/user/${receiver_user_id}/token`).once('value');
return DeviceToken.then(result =>
{
const token_id = result.val();
const payload =
{
notification:
{
title: "Open this notification now",
body: `I have a problem in my car `,
icon: "default" ,
sound: "default"
}
};
return admin.messaging().sendToDevice(token_id, payload)
.then(response =>
{
console.log('This was a notification feature.');
});
});
});
thats all i have to describe my issue
Yes, you can deploy various functions, but you need to set different names for each one of them. The function name is after exports., so you can have:
exports.sendNotification
exports.newMessageNotification
exports.newFollowerNotification
...
and each one of them will make what you wish them to do.
I want to send notification to users when they receive new messages with the below JavaScript code
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.pushNotification = functions.database.ref('/messages/{user_id}/{message_id}').onWrite( (change, context) => {
const user_id = context.params.user_id;
const message_id = context.params.message_id;
console.log('We Have A Notification for :', user_id);
if (!change.after.val()){
return console.log("A Notification Has Been Deleted From The Database: ", message_id)
}
const fromUser = admin.database().ref(`/messages/${user_id}/${message_id}`).once('value');
return fromUser.then(fromUserResult => {
const from_user_id = fromUserResult.val().from;
console.log("You have new notification from : ", from_user_id)
const userQuery = admin.database().ref(`/Users/${from_user_id}/name`).once('value');
const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
return Promise.all([userQuery, deviceToken]).then(result => {
const userName = result[0].val();
const token_id = result[1].val();
const payload = {
notification: {
title: "Chat+",
body: `You have a new notification from ${userName}`,
icon: "default",
click_action: "com.mani.eric.quickch_TARGET_NOTIFICATION"
},
};
return admin.messaging().sendToDevice(token_id, payload ).then(Response =>{
console.log('this is the notification')
});
});
});
});
the notification actually gets delivered but on both devices(sender and receiver gets same notification) with the user name of the sender as null.
my question now is, how can i retrieve the sender user name and display the notification only on the receivers device?
You have a type on the path that triggers the function:
functions.database.ref('/messages/{user_id/{message_id}')
Should be:
functions.database.ref('/messages/{user_id}/{message_id}')
So with a closing parenthesis after user_id.
Please read how to create a minimal, complete, verifiable example, as the code you shared is quite a bit more complex than needed to reproduce the problem. For example, your console.log('We Have A Notification for :', user_id); already should show that user_id is null, so the code after that can't work, and is irrelevant to the problem. Reducing the scope of the problem this way increases the chances that you'll find the cause yourself. Or at worst, it reduces the code we need to look at, which increases the chance that somebody will spot the problem and answer.
I need to send notification when data change in my Cloud Firestore database. I have this fields
I need to get the all users tokens and send the push notification. I have a code, but this only give me a token if i know the user name this is my code :
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.useWildcard = functions.firestore
.document('notification/{id}')
.onWrite((change, context) => {
const payload = {
notification: {
title: 'Message from Cloud',
body: 'This is your body',
badge: '1',
sound: 'default'
}
};
admin.firestore().collection('notification').doc('fcm-token').get().then(doc => {
console.log("Token: " + doc.data().user1.token);
});
});
To loop over all users in the document:
admin.firestore().collection('notification').doc('fcm-token').get().then(doc => {
let data = doc.data();
Object.keys(data).forEach((user) {
console.log("Token: " + data[user].token);
});
});
But as Doug commented: storing the tokens for all users in a single document is bound to become a scalability problem at some point.
I am receiving default push notification instead of my own payload data
in notification.
Here you can see the notification in this Picture below
I am getting no errors on firebase log, also receiving data which I want to send through push notification
Here you can see
and here is the code of index.js file of firebase cloud function
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotifications = functions.database.ref(`messages/{notificationId}`).onCreate((event) => {
const receiverId = event.val().recId;
const payload = {
notification: {
title: `New Message from ${event.val().sndrName}!`,
body: event.val().message,
status: "New message",
icon: 'icon-192x192.png'
}
}
console.info(payload);
let tokensList = [];
return admin.database().ref('fcmtokens').orderByValue().equalTo(receiverId).once('value').then((token) => {
console.info(token.val());
if(token.val()) {
tokensList = (Object.keys(token.val()));
console.info(tokensList);
return admin.messaging().sendToDevice(tokensList,payload);
}
})
})
I am very new to firebase cloud functions please tell if I am doing something wrong,TIA