Error sending notification through firebase function flutter - node.js

I am trying to send push notification to the user whenever the new event is added into the firestore of the firebase.
Whenever I do so it returns me the error saying Error sending notification
node.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().functions);
var newData;
exports.messageTrigger = functions.firestore.document('Messages/{messageId}').onCreate(async(snapshot, context)=> {
if(snapshot.empty){
console.log('No Devices');
return;
}
var tokens = ['mobile-token'];
newData = snapshot.data();
var payload = {
notification : {title: 'Push Title', body: 'Push body', sound: 'default'},
data: {click_action: 'FLUTTER_NOTIFICATION_CLICK', message: newData.message},
};
try{
const response = await admin.messaging.sendToDevice(tokens, payload);
console.log('Notification sent successfully');
} catch (err) {
console.log('Error sending notifications');
}
});
I am passing the mobile token in place of mobile-token

SOLUTION
Changing admin.messaging.sendToDevice() to
const response = await admin.messaging().sendToDevice(tokens, payload)
As admin.messaging.sendToDevice() is not a method

Related

Function returned undefined, expected Promise or value Firebase log error

Im trying to add a push notification on my app using firebase-function and node.js and all its all working fine, like I got notification from the sender. but my only concern is that the log gave me this error
Function returned undefined, expected Promise or value
and this is my code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification : ', user_id);
const afterData = change.after.val();
if (!afterData){
return console.log('A notification has been deleted from the database', notification_id);
}
const fromUser = admin.database().ref(`/notifications/${user_id}/${notification_id}`).once('value');
return fromUser.then(fromUserResult => {
const from_user_id = fromUserResult.val().from;
console.log('You have a new notification from: ', from_user_id);
const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
return deviceToken.then(result => {
const token_id = result.val();
const payload = {
notification: {
title: "New Friend Request",
body: "You've received a new Friend Request",
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id, payload).then(response => {
console.log('This was the notification feature');
});
});
});
});
what should I return here and where it will be place? I am currently using the latest firebase CFM version 1.0
This line could be causing the error message:
return console.log('A notification has been deleted from the database', notification_id);
When this line is hit, you're effectively returning undefined from the function, because that's what console.log() returns. Instead, you should just return null after the log.

Why am I Getting Duplicate Notifications?

I'm trying to use Firebase functions to automatically send push notifications to iOS devices. More specifically, right now when a user creates a post, it will contain an ID, which is actually the user's FCM token, from which the push notification will be sent to that user.
Why does it happen that, upon creating a post, my iOS device doesn't necessarily receive a single push notification, but many? Why is the getResult function being triggered potentially more than once for a given post?
Please see my code below. Thanks!
const functions = require('firebase-functions');
var admin = require('firebase-admin');
var firebase = require('firebase');
admin.initializeApp(functions.config().firebase);
var config = {
apiKey: "XXXXX",
authDomain: "YYYYY",
databaseURL: "ZZZZZ"
}
firebase.initializeApp(config);
firebase.database().ref('posts').on('child_added', function(snapshot1) {
snapshot1.forEach((child) => {
if (child.key == 'id') {
var token = child.val();
admin.database().ref('users').on('value', function(snapshot2) {
snapshot2.forEach(function(user) {
if (user.val().fcmToken == token) {
var newBadgeCount = user.val().badge + 1;
const payload = {
notification: {
title: 'Hello, World!',
body: 'Test Message!',
badge: '' + newBadgeCount,
sound: 'default'
}
};
function getResult(token) {
return result = admin.database().ref('fcmToken/' + token).once('value').then(allToken => {
if (allToken.val()) {
const token = Object.keys(allToken.val());
return admin.messaging().sendToDevice(token, payload).then(function (response) {
console.log("Successfully sent message: ", response.results[0].error);
}).catch(function (error) {
console.log("Error sending message: ", error);
});
};
});
}
function updateBadgeCount(badgeCount, userID) {
firebase.database().ref('users/' + userID + '/badge').set(badgeCount);
}
Promise.all([getResult(token)]).then(function(snapshots) {
updateBadgeCount(newBadgeCount, user.key);
});
};
});
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
};
});
});
Firebase triggers for each record of all records with 'child_added' option once and will re-trigger after each new child added. So, If you like to trigger a function on new write options, you need use other ways.
exports.sendNotifycation = functions.database.ref('/posts/{postId}')
.onWrite(event => {
Your new re-designed codes. (in case I will complete remain)
})

How to send notification to all user except the sender in android using node js firebase function

I have a firebase cloud functions to send notifications to topics. The problem is that it sends to all users including the sender, while I don't want it to send to the sender. Please don't give a example of subscribe and unsubscribe example as I could not understand this solution. Please help?
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.pushNotification = functions.database.ref('/messages/{pushId}').onWrite( event => {
console.log('Push notification event triggered');
var message1 = event.data.val();
if (!message1) {
return;
}
var valueObject = message1.messageText;
console.log('Push notification event triggered '+valueObject);
const payload = {
notification: {
title:'Chat app',
body: valueObject,
},
};
const options = {
priority: "high",
timeToLive: 0 * 0 * 0
};
return admin.messaging().sendToTopic("pushNotifications", payload, options).then(function(response) {
console.log("Successfully sent message:", response);
return event.data.adminRef.vel();
})
.catch(function(error) {
console.log("Error sending message:", error);
});
});
Thanks in advance!

How to get push notification in FCM when child is added in Firebase?

Notification is to be sent when a child is added to /ADMIN/Orders
The notification has to be sent to each user who have the same Token ID
My node.js code is
'use strict'
var topic = "Users";
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.updateOrder =
functions.database.ref('/ADMIN/Orders/{order_id}').onWrite(event =>{
const order_id = event.params.order_id;
console.log("Today's order is updated!",order_id);
const deviceToken = admin.database().ref(`/USERS/{user_id}/TokenId`).once('value');
return deviceToken.then(result => {
const TokenId = result.val();
const payload = {
notification: {
title: "Order is updated!",
body: "Click to enter Yes/No",
icon: "default"
}
};
// return admin.messaging().sendToDevice(TokenId,payload).then(response =>{
return admin.messaging().sendToTopic(topic, payload).then(response =>{
console.log('This was the notification feature');
});
});
});
My cloud function(.js file) is showing successful execution, but still the push notificaiton is not appearing on my phone.

How to send push notifications to specific users with Cloud Functions for Firebase

I am using Firebase as my back end for my Android app and am very new to using Cloud Functions for Firebase and I was wondering how I would send specific users push notification when an event occurs.
For example how would I send the user with uId in the below code a push notification when a write occurs at adminName node on the database:
exports.sendNotification = functions.database.ref('/users/{uId}/groups/{adminName}')
.onWrite(event => {
// Grab the current value of what was written to the Realtime Database.
var eventSnapshot = event.data;
var str1 = "Author is ";
var str = str1.concat(eventSnapshot.child("author").val());
console.log(str);
var topic = "android";
var payload = {
data: {
title: eventSnapshot.child("title").val(),
author: eventSnapshot.child("author").val()
}
};
// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToTopic(topic, payload)
.then(function (response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
Make the below changes. it works for me
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().functions);
var newData;
exports.myTrigger = functions.firestore.document('TestCollection/{id}').onWrite(async (snapshot, context) => {
//
if (snapshot.empty) {
console.log('No Devices');
return;
}
newData = snapshot.data();
const deviceIdTokens = await admin
.firestore()
.collection('DeviceIDTokens')
.get();
var tokens = [];
for (var token of deviceIdTokens.docs) {
tokens.push(token.data().device_token);
}
var payload = {
notification: {
title: 'Push Title',
body: 'Push Body',
sound: 'default',
},
data: {
push_key: 'Push Key Value',
key1: newData.data,
},
};
try {
const response = await admin.messaging().sendToDevice(tokens, payload);
console.log('Notification sent successfully');
} catch (err) {
console.log(err);
}
});

Resources