Javascript if conditional variable problem - javascript

I have two receiver type. 0 for guests 1 for users. I'm trying to push notification from firebase cloud functions. I can send notification user to guest succesfully. But can not send notification guest to user. Is there any problem with my if condition?
var usersRef = null;
if (receiverType === 0) {
usersRef = admin.firestore().collection('Guests').doc(receiverId);
} else {
usersRef = admin.firestore().collection('Users').doc(receiverId);
}
I want to change var usersRef variable based on receiverType. I managed to change it to Guest path but on the else part its path must change again to Users. But not changing. There is a problem in my if else statement.
var getDoc = usersRef.get()
.then(doc => {
if (!doc.exists) {
return null;
} else {
const token = doc.data().token;
const payload = {
notification: {
title: "New Message",
body: chatMessage,
}
};
admin.messaging().sendToDevice(token, payload)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
return null;
})
.catch((error) => {
console.log('Error sending message:', error);
return null;
});
}
return null;
})
.catch(err => {
console.log('Error getting document', err);
return null;
});
return null;
});

Related

Error "Function returned undefined, expected Promise or value" even after return in all places

I am new to Node.js and I am struggling with Promises even after reading the tutorials provided by other stackflow users. I have already spent a whole evening on this and I am looking for help. I get the following error " Function returned undefined, expected Promise or value". My code is below. What am I doing wrong? I also have a suspicion that I have to use await/async because it looks like my code is running through without waiting for the first get to complete.
const admin = require('firebase-admin');
const functions = require('firebase-functions');
var db = admin.firestore();
exports.declinedRequest = functions.firestore
.document('requests/{requestId}')
.onUpdate((change, context) => {
const newValue = change.after.data();
const status = newValue.status;
const request = context.params.requestId;
var registrationToken;
var message;
if(status=="created") {
console.log('Checkpoint1 ',context.params.requestId);
newValue.friends.forEach(doc => {
console.log('Checkpoint 2: ', doc);
var usersRef = db.collection('users');
var query = usersRef.where('mobile', '==', doc).get()
.then(snapshotFriend => {
if (snapshotFriend.empty) {
console.log('Checkpoint3.');
return;
}
snapshotFriend.forEach(mobile => {
registrationToken = mobile.data().fcmToken;
console.log('FCM token =>', registrationToken);
if (!registrationToken) {
console.log('No fcmToken available');
return;
}
message = {
notification: {
body: "Request still available from " + newValue.requesterName,
sound: "default",
badge: 1
},
data: {
requestId: `${request}`
}
};
console.log('FCM token message created');
})
})
})
} else {
return;
}
return admin.messaging().sendToDevice(registrationToken, message)
.then(function (response) {
console.log("Successfully sent message:", response)
})
.catch(function (error) {
console.log("Error sending message:", error);
})
})
Try the code below hope this will work.
const admin = require('firebase-admin');
const functions = require('firebase-functions');
const Promise = require('bluebird');
const _ = require('lodash');
let db = admin.firestore();
exports.declinedRequest = functions.firestore
.document('requests/{requestId}')
.onUpdate((change, context) => {
const newValue = change.after.data();
const status = newValue.status;
const request = context.params.requestId;
if (status == "created") {
console.log('Checkpoint1 ', context.params.requestId);
allPromises = [];
newValue.friends.forEach(doc => {
console.log('Checkpoint 2: ', doc);
const usersRef = db.collection('users');
// query for each document return promise.
allPromises.push(queryForEachDocument(doc,request,usersRef));
});
return Promise.all(allPromises);
} else {
return Promise.reject / resolve('Whatever you want.');
}
})
function queryForEachDocument(doc,request,usersRef) {
let promiseInvoices = []
let registrationToken;
let message;
return usersRef.where('mobile', '==', doc).get().then((snapshotFriend) => {
if (_.isEmpty(snapshotFriend)) {
console.log('Checkpoint3.');
return Promise.reject(new Error('Your error'));
}
snapshotFriend.forEach(mobile => {
registrationToken = mobile.data().fcmToken;
console.log('FCM token =>', registrationToken);
if (!registrationToken) {
console.log('No fcmToken available for', newValue.requesterName);
// Do anything you want to change here.
return Promise.reject(new Error('No fcmToken available for',newValue.requesterName));
}
message = {
notification: {
body: "Request still available from " + newValue.requesterName,
sound: "default",
badge: 1
},
data: {
requestId: request
}
};
console.log('FCM token message created');
// send invoice for each registrationToken
promiseInvoices.push(sendInvoice(registrationToken, message))
});
}).then(() => {
return Promise.all(promiseInvoices);
})
}
function sendInvoice(registrationToken, message) {
return admin.messaging().sendToDevice(registrationToken, message)
.then(function (response) {
console.log("Successfully sent message:", response)
})
.catch(function (error) {
console.log("Error sending message:", error);
})
}

High Delay in FCM when sent through Firebase Functions

I'm trying to send FCM using Firebase Functions, This is the code I'm using
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
admin.firestore().settings({
timestampsInSnapshots: true
});
var token = 'token_value';
var sender = 'sender_value';
var reciever = 'reciever_value';
var message = 'message_value';
var payload ='payload_value';
var db = admin.firestore();
exports.sendFollowerNotification =
functions.database.ref('/m/{messageid}')
.onCreate((snapshot, context) => {
console.log('v21');
message = context.params.messageid;
console.log('Message Id:', message);
reciever = snapshot.val().r;
console.log('Message reciever: ', reciever);
sender = snapshot.val().s;
console.log('Message sender: ', sender);
payload = {
data: {
id: `${message}`,
sender: `${sender}`
}
};
console.log('Payload Created');
var tokenRef = db.collection(reciever).doc('t');
console.log('Fetching Token');
tokenRef.get()
.then(doc => {
console.log('Fetching Token started');
if (!doc.exists) {
console.log('Token doesnt exist ');
} else {
token = doc.data().v;
console.log('Token data:', token);
}
console.log('End Then');
return token;
})
.catch(err => {
console.log('Error getting token', err);
}).then((token) => {
console.log('Sending FCM now');
admin.messaging().sendToDevice(token,payload);
return console.log('Successfully sent message:');
})
.catch((error) => {
console.log('Error sending message:', error);
});
})
The problem is that FCM is received with huge delay(about 40s), however fcm sent from Firebase Console is received almost immediately (about 2-3s).
Since I am an android developer and have no experience of Node.js, I believe that something is wrong with JS code. Help me by telling whats wrong or possible workaround.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
admin.firestore().settings({
timestampsInSnapshots: true
});
var db = admin.firestore();
function debugLogger(msg) {
// comment out to disable logging
console.log(msg);
}
function errLogger(err) {
console.log(err);
}
exports.sendFollowerNotification =
functions.database.ref('/m/{messageid}')
.onCreate((snapshot, context) => {
debugLogger('v23_stackoverflow');
const message = context.params.messageid;
debugLogger(`Message Id: ${message}`);
const reciever = snapshot.val().r;
debugLogger(`Message reciever: ${reciever}`);
const sender = snapshot.val().s;
debugLogger(`Message sender: ${sender}`);
const payload = {
data: {
id: `${message}`,
sender: `${sender}`
}
};
debugLogger('Payload Created');
let tokenRef = db.collection(reciever).doc('t');
debugLogger('Fetching Token');
return tokenRef.get()
.then(doc => {
debugLogger('Fetching Token started');
if (!doc.exists)
throw new Error("Token doesnt exist");
let token = doc.data().v;
debugLogger(`Token data: ${token}`);
return token;
})
.then(token => {
debugLogger('Sending FCM now');
return admin.messaging().sendToDevice(token, payload);
})
.then(() => {
debugLogger('Successfully sent message!');
return null;
})
.catch(err => {
errLogger(err);
})
})

Inconsistent results from Firestore Cloud Functions

I have a Cloud Function setup on Firebase that involved checking different parts of the Firestore Database and then sending a message via Cloud Messaging
Below is the JavaScript for the function in question:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().Firebase);
var db = admin.firestore();
exports.newMemberNotification = functions.firestore
.document('Teams/{teamId}/Waitlist/{userId}').onDelete((snap, context) => {
// get the user we want to send the message to
const newValue = snap.data();
const teamidno = context.params.teamId;
const useridno = newValue.userID;
//start retrieving Waitlist user's messaging token to send them a message
var tokenRef = db.collection('Users').doc(useridno);
tokenRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
const data = doc.data();
//get the messaging token
var token = data.messaging_token;
console.log("token: ", token);
//reference for the members collection
var memberRef = db.collection('Teams/'+teamidno+' /Members').doc(useridno);
memberRef.get()
.then(doc => {
if (!doc.exists){
console.log('user was not added to team. Informing them');
const negPayload = {
data: {
data_type:"team_rejection",
title:"Request denied",
message: "Your request to join the team has been denied",
}
};
return admin.messaging().sendToDevice(token, negPayload)
.then(function(response){
console.log("Successfully sent rejection message:", response);
return 0;
})
.catch(function(error){
console.log("Error sending rejection message: ", error);
});
} else {
console.log('user was added to the team. Informing them')
const payload = {
data: {
data_type: "team_accept",
title: "Request approved",
message: "You have been added to the team",
}
};
return admin.messaging().sendToDevice(token, payload)
.then(function(response){
console.log("Successfully sent accept message:", response);
return 0;
})
.catch(function(error){
console.log("Error sending accept message: ", error);
});
}
})
.catch(err => {
console.log('Error getting member', err);
});
}
return 0;
})
.catch(err => {
console.log('Error getting token', err);
});
return 0;
});
The issues I have with this are:
The code runs and only sometimes actually checks for the token or sends a message.
the logs show this error when the function runs: "Function returned undefined, expected Promise or value " but as per another Stack Oveflow posts, I have added return 0; everywhere a .then ends.
I am VERY new to node.js, javascript and Cloud Functions so I am unsure what is going wrong or if this is an issue on Firebase's end. Any help you can give will be greatly appreciated
As Doug said, you have to return a promise at each "step" and chain the steps:
the following code should work:
exports.newMemberNotification = functions.firestore
.document('Teams/{teamId}/Waitlist/{userId}').onDelete((snap, context) => {
// get the user we want to send the message to
const newValue = snap.data();
const teamidno = context.params.teamId;
const useridno = newValue.userID;
//start retrieving Waitlist user's messaging token to send them a message
var tokenRef = db.collection('Users').doc(useridno);
tokenRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
throw 'No such document!';
} else {
const data = doc.data();
//get the messaging token
var token = data.messaging_token;
console.log("token: ", token);
//reference for the members collection
var memberRef = db.collection('Teams/' + teamidno + '/Members').doc(useridno);
return memberRef.get()
}
})
.then(doc => {
let payload;
if (!doc.exists) {
console.log('user was not added to team. Informing them');
payload = {
data: {
data_type: "team_rejection",
title: "Request denied",
message: "Your request to join the team has been denied",
}
};
} else {
console.log('user was added to the team. Informing them')
payload = {
data: {
data_type: "team_accept",
title: "Request approved",
message: "You have been added to the team",
}
};
}
return admin.messaging().sendToDevice(token, payload);
})
.catch(err => {
console.log(err);
});
});

Firebase Sends Notification for removeValue Operation

So I have a functionality in my app wherein a user can post or delete any alert. If a new alert is posted other users must get a notification regarding it. Firebase push notification works good when a new data is added to the database but if a post has been deleted (dataRef.child(root_child).removeValue();) it still sends notification to the user which is not required. How to handle this situation?
index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotificationAlert = functions.database.ref(`AlertPost/{pushId}`).onWrite(event => {
const getDeviceTokensPromise = admin.database().ref(`/Token/token_no`).once('value');
const getBody=admin.database().ref(`/AlertPost`).once('value');
var title_input='You have a new Alert';
var contentAlert = event.data.val();
var body_input=contentAlert.description;
//const tokensSnapshot = results[0];
return Promise.all([getDeviceTokensPromise,getBody]).then(results => {
const tokensSnapshot = results[0];
const notify=results[1];
if (!tokensSnapshot.hasChildren()) {
return console.log('There are no notification tokens to send to.');
}
console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
var contentAlert = event.data.val();
// Notification details.
const payload = {
data: {
title: title_input,
body: body_input
//icon: follower.photoURL
},
notification: {
title: title_input,
body: body_input
}
};
const tokens = Object.keys(tokensSnapshot.val());
//token_send(admin,tokensSnapshot,tokens,payload,title_input);
// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
console.log("Successfully sent message:", response);
// For each message check if there was an error.
const tokensToRemove = [];
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
console.error('Failure sending notification to', tokens[index], error);
// Cleanup the tokens who are not registered anymore.
if (error.code === 'messaging/invalid-registration-token' ||
error.code === 'messaging/registration-token-not-registered') {
tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
}
}
});
return Promise.all(tokensToRemove);
});
});
});
You could check if the previous value of the event DataSnapshot is already deleted. Check this documentation for more information.
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').onWrite((event) => {
// Only edit data when it is first created.
if (event.data.previous.exists()) {
return;
}
// Exit when the data is deleted.
if (!event.data.exists()) {
return;
}
});
You could also check this SO post for reference.

I'm trying to give notification by Firebase cloud function, but my code doesn't give any notification

I have done authentication trigger, it's working fine. If someone delete their account I need to send to notification "this user deleted his account (email)" like that. Here is my code
const functions = require('firebase-functions')
//initialize the app
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
const ref = admin.database().ref()
//create user account function
exports.createUserAccount = functions.auth.user().onCreate(event => {
const uid = event.data.uid
const email = event.data.email
const newUserRef = ref.child(`/UserNotify/${uid}`)
return newUserRef.set({
email: email
})
})
//delete user account function
exports.cleanupUserData = functions.auth.user().onDelete(event => {
const uid = event.data.uid
const userRef = ref.child(`/UserNotify/${uid}`)
return userRef.update({isDeleted: true})
})
function sendNotification() {
console.log("Successfully sent");
var payload = {
notification: {
title: "User get deleted",
body: "sample#gmail.com"
}
};
admin.messaging().sendToDeveice(payload)
.then(function (response) {
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
})
}
You may have a typing error
admin.messaging().sendToDevice() and not sendToDeveice
check: https://firebase.google.com/docs/cloud-messaging/admin/send-messages

Categories

Resources