How do I resolve FCM Cloud function npm errors? - firebase

error Expected catch() or return promise/catch-or-return
23:13 error Each then() should return a value or throw promise/always-return
28:13 error Expected catch() or return promise/catch-or-return
28:13 warning Avoid nesting promises promise/no-nesting
33:21 error Each then() should return a value or throw promise/always-return
45:19 warning Avoid nesting promises promise/no-nesting
45 :19 warning Avoid nesting promises promise/no-nesting
48:27 error Each then() should return a value or throw '
Above code is error content (terminal Mac Os), since terminal deployed, this error code shows up.
I follow firebase contents and read some time, but I don't know.
Firebase justify:
"Send messages to specific devices
To send a message to one specific device, forward the device's registration token as shown below. For more information about registration tokens, see About Client Settings by Platform."
I am using FCM push message, but only deployed, this code show
this code is showing push message to specified person's uid.
Some error distress me, and this is my code(exactly this is other person code (flutter FCM demo)
const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp()
exports.sendNotification = functions.firestore
.document('messages/{groupId1}/{groupId2}/{message}')
.onCreate((snap, context) => {
console.log('----------------start function--------------------')
const doc = snap.data()
console.log(doc)
const idFrom = doc.idFrom
const idTo = doc.idTo
const contentMessage = doc.content
// Get push token user to (receive)
admin
.firestore()
.collection('user')
.where('uid', '==', idTo)
.get()
.then(querySnapshot => {
querySnapshot.forEach(userTo => {
console.log(`Found user to: ${userTo.data().nickname}`)
if (userTo.data().pushToken && userTo.data().chattingWith !== idFrom) {
// Get info user from (sent)
admin
.firestore()
.collection('users')
.where('id', '==', idFrom)
.get()
.then(querySnapshot2 => {
querySnapshot2.forEach(userFrom => {
console.log(`Found user from: ${userFrom.data().nickname}`)
const payload = {
notification: {
title: `You have a message from "${userFrom.data().nickname}"`,
body: contentMessage,
badge: '1',
sound: 'default'
}
}
// Let push to the target device
admin
.messaging()
.sendToDevice(userTo.data().pushToken, payload)
.then(response => {
console.log('Successfully sent message:', response)
})
.catch(error => {
console.log('Error sending message:', error)
})
})
})
} else {
console.log('Can not find pushToken target user')
}
})
})
return null
})

Related

Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array. (Firebase cloud functions)

I am making a chat application where I am trying to send push notifications to when one user sends a message to the other user.
I am using firebase cloud functions with JavaScript and in the firebase functions log I can see that it's able to get the user who sends the message and the user who receives the message. But for some reason It's showing me that the token is empty.
Even though I have a token and I am able to print it in the log(The screenshot of firebase cloud functions log where you can see that token is being printed and I have partially marked over it).
For more reference I am also attaching the screenshot of my two collections in firebase -
All the users collection where the push token is being saved.(The structure is users>uid>{user_info}).
The chat collection screenshot where you can see the structure of chats.(The structure here is chatroom>chatid>chats>{chat_documents}).
My index.js file in functions folder for firebase is below-
const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp()
exports.sendNotification = functions.firestore
.document('chatroom/{chatId}/chats/{message}')
.onCreate((snap) => {
console.log('----------------start function--------------------')
const doc = snap.data()
console.log(doc)
const idFrom = doc.idFrom
const idTo = doc.idTo
const contentMessage = doc.mesaage
console.log(`Starting to push token`)
// Get push token user to (receive)
admin
.firestore()
.collection('users')
.where('uid', '==', idTo)
.get()
.then(querySnapshot => {
querySnapshot.forEach(userTo => {
console.log(`Found user to: ${userTo.data().name}`)
console.log(`Found user to: ${userTo.data().pushtoken}`)
try {
// Get info of the user who is sending the message
admin
.firestore()
.collection('users')
.where('uid', '==', idFrom)
.get()
.then(querySnapshot2 => {
querySnapshot2.forEach(userFrom => {
console.log(`Found user from: ${userFrom.data().name}`)
const payload = {
notification: {
title: `"${userFrom.data().name}"`,
body: contentMessage,
badge: '1',
sound: 'default'
}
}
// Lets push to the target device
admin
.messaging()
.sendToDevice(payload,userTo.data().pushtoken)
.then(response => {
console.log('Successfully sent message:', response)
})
.catch(error => {
console.log('Error sending message:', error)
})
})
})
} catch(e){
console.log('Can not find pushToken target user')
}
})
})
return null
})
What might be the problem here as I am not able to figure it out? Your help would be really appreciated. Also kindly let me know if you want any more information regarding the same.

Firebase functions cloud messaging notification not being recieved

When I send a notification from the Firebase cloud messaging console, my device receives it without a problem, but when I send it via a cloud functions, the function log says it was successfully sent but my device does not receive it. I tried switching to type script, sending the notification with different conditions but nothing works. The app is written in flutter.
My function code:
exports.sendNotification = functions.https.onRequest((request, response) => {
const db = admin.firestore();
const fcm = admin.messaging();
db.collection("users")
.where("bananas", "==", 1666).get().then(
(result) => {
if (result.size > 0) {
result.forEach((doc) => {
const payload = {
token: doc.data().NotToken,
notification: {
title: "iam a notification",
body: "Yay",
icon: "https://cdn1.iconfinder.com/data/icons/logos-brands-in-colors/231/among-us-player-white-512.png",
},
};
fcm.send(payload).then((response) => {
// Response is a message ID string.
console.log("Successfully sent message: "+
doc.data().NotToken+ " ", response);
return {success: true};
}).catch((error) => {
return {error: error.code};
});
});
}
});
response.send("Notification sent !");
functions.logger.info("Notification sent!");
return null;
});
cloud log
Any ideas?
Did you notice how your code never logs this message?
Successfully sent message
That's because both loading from Firestore, and sending messaging through Cloud Messaging are asynchronous calls. So your response.send("Notification sent !") runs before the data is ever retrieved from the database, and Cloud Functions at that point terminates your code to prevent charging after you say that you are done.
If you have asynchronous operations in your code, you need to return a promise from the top-level of your code that resolves/rejects when all asynchronous code has completed. So in your case that means the promise should only resolve once you've loaded the data from Firestore, and sent the messages.
Let's start with a simple example. Say that you want to only send a single message, no matter how many documents are in the database.
exports.sendNotification = functions.https.onRequest((request, response) => {
const db = admin.firestore();
const fcm = admin.messaging();
return db.collection("users") // 👈 Add return here
.where("bananas", "==", 1666).get().then((result) => {
if (result.size > 0) {
const doc = result.docs[0]; // 👈 Get the first result
const payload = {
token: doc.data().NotToken,
notification: {
title: "iam a notification",
body: "Yay",
icon: "https://cdn1.iconfinder.com/data/icons/logos-brands-in-colors/231/among-us-player-white-512.png",
},
};
return fcm.send(payload).then((response) => { // 👈 Add return here
console.log("Successfully sent message: "+
doc.data().NotToken+ " ", response);
response.send("Notification sent !"); // 👈 Move this call here
return {success: true};
}).catch((error) => {
// TODO: Send an error back to the caller
return {error: error.code};
});
}
});
});
So the top-level code now returns the result from loading data from Firestore, and in there, we return the call from calling FCM, which then in turn returns return {success: true};. When returning promises, the results bubble up - so you can typically just keep returning the nested results.
You'll also not that we've moved the response.send into the code that runs after calling FCM, as we don't want to send a result back to the caller until the FCM call is done.
The above is the simple variant, because in reality you have multiple documents, and you are only done once all of them are done.
For that we are going to use Promise.all(), which takes an array of promises and resolves once all those promises resolve. So we're going to capture all the calls to FCM (which returns a promise) and collection them in an array, that we then pass to Promise.all().
exports.sendNotification = functions.https.onRequest((request, response) => {
const db = admin.firestore();
const fcm = admin.messaging();
return db.collection("users")
.where("bananas", "==", 1666).get().then((result) => {
if (result.size > 0) {
let promises = [];
result.forEach((doc) => {
const payload = {
token: doc.data().NotToken,
notification: {
title: "iam a notification",
body: "Yay",
icon: "https://cdn1.iconfinder.com/data/icons/logos-brands-in-colors/231/among-us-player-white-512.png",
},
};
promises.push(fcm.send(payload))
});
return Promise.al(promises).then((results) => {
console.log("Successfully sent messages");
response.send("Notification sent !");
return {success: true};
});
}
});
});
While this may be a lot to grok all at once, handling asynchronous behavior is quite well covered in the Firebase documentation on terminating functions, in this video series on Learn JavaScript Promises with Cloud Functions, and in quite a few tutorials out there - so I recommend spending some time on those to get to grips with asynchronous code.

CloudFunctions: Request is sending twice

I have an issue and I need help since I'm learning.
I have a flutter app that saves on Firebase/Firestore data, when a user requests a friendship I add it on both sender and target user, changing the IDs of sendTo and sentBy.
My problem is that CloudFunctions detect well that 2 collections from different users have been changed and notify me 2x (target user). So code is fine but should only notify once/target user
I'm using FCM to send local notifications.
exports.sendRequestNotification = functions.firestore
.document('users/{userId}/requests/{requestId}')
.onCreate((snap, context) => {
const docReq = snap.data()
/*console.log(docReq)*/
const sentBy = docReq.sentBy
const sentTo = docReq.sentTo
const contentRequest = docReq.code
if(contentRequest !== null){
// Get push token user to (receive)
admin
.firestore()
.collection('users')
.where('userId', '==', sentTo)
.get()
.then(querySnapshot => {
querySnapshot.forEach(userTo => {
/*console.log(`Found request user to: ${userTo.data().userId}`)*/
if (userTo.data().pushToken) {
// Get info user from (sent)
admin
.firestore()
.collection('users')
.where('userId', '==', sentBy)
.get()
.then(querySnapshot2 => {
querySnapshot2.forEach(userFrom => {
/*console.log(`Found request user from: ${userFrom.data().userId}`)*/
const payload = {
notification: {
title: `${userFrom.data().nickname}`,
body: contentRequest,
badge: '1',
sound: 'default'
}
}
// Let push to the target device
admin
.messaging()
.sendToDevice(userTo.data().pushToken, payload)
.then(response => {
/*console.log('Successfully sent request:', response)*/
})
.catch(error => {
console.log('Error sending request:', error)
})
})
})
} else {
console.log('User request or token not found')
}
})
})
return null
}
})
It is not very clear from your code why it would send the notification twice (since you check that userTo.data().userId !== sentBy). But what is sure is that you are not returning a Promise that resolves when all the asynchronous operations (get() and sendToDevice()) are completed.
I would suggest you watch the official Video Series (https://firebase.google.com/docs/functions/video-series/) which explain very well this point about returning Promises for background functions (in particular the ones titled "Learn JavaScript Promises").
In particular, you will see in the videos that if you don't return a Promise, the Cloud Function may terminate before asynchronous operations are completed, potentially resulting in some inconsistent (not logical) results .
So, you should give a try with the following adapted code, which returns the promises chain:
exports.sendRequestNotification = functions.firestore
.document('users/{userId}/requests/{requestId}')
.onCreate((snap, context) => {
const db = admin.firestore();
const docReq = snap.data();
/*console.log(docReq)*/
const sentBy = docReq.sentBy;
const sentTo = docReq.sentTo;
// Get push token user to (receive)
return db.collection('users')
.where('userId', '==', sentTo)
.get()
.then(querySnapshot => {
//We know there is only one document (i.e. one user with this Id), so lets use the docs property
//See https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot.html#docs
const userTo = querySnapshot.docs[0];
if (userTo.data().pushToken && userTo.data().userId !== sentBy) {
// Get info user from (sent)
return db.collection('users')
.where('userId', '==', sentBy)
.get();
} else {
console.log('User request or token not found')
throw new Error('User request or token not found');
}
})
.then(querySnapshot => {
const userFrom = querySnapshot.docs[0];
const payload = {
notification: {
title: `${userFrom.data().nickname}`,
body: `requestNotify`,
badge: '1',
sound: 'default'
}
}
return admin
.messaging()
.sendToDevice(userTo.data().pushToken, payload);
})
.catch(error => {
console.log('Error:', error);
return false;
})
})

Firebase functions just dying out with no explanation or error

I'm trying to implement a messaging application using Firebase Firestore and Firebase Cloud Functions.
In essence, chat messages are stored as individual documents in a subcollection. At first, I implemented this as directly adding a document from the client and listening on the collection and updating the clients when a change happens but later I decided to switch to using Cloud functions so that I can add some functionality that's better done on the server side(filtering etc.).
So I created a function for sending messages, which creates the documents on behalf of the users when the users call the function from the app(i.e. tap the send button).
The function worked and I was able to monitor the processes through the logs. Unfortunately, the functions began to die out without error, the console was reporting that the functions are executed successfully and it usually took less than a second to execute.
I suspect that it has something to do with the promises that probably continue to run but this is the same code that was working but failing today.
If I try a few more times, the functions seem to be working again. Do I need to keep the functions "warm"? Are cloud functions not reliable enough to handle this kind of tasks? When I say my user that a message is sent, I need to be able to confirm that it is sent and communicate it with the users if it failed.
It's hard to debug the issue because no errors are thrown(not even info message, it's just as if didn't happen), it just says that the function successfully finished execution and nothing happened.
Am I missing something here? Thank you.
exports.sendMessage = functions.https.onCall((data, context) => {
if (context.auth.uid == undefined) {
console.warn("SEND MESSAGE: USER NOT SIGNED IN");
return;
}
console.log("Sending message:", data)
const matchId = data["matchId"];
const message = data["message"]
const uid = context.auth.uid
admin.firestore().collection(MatchingUsers).doc(matchId).collection(UserMessages).add({
type: "text",
from: uid,
message: message,
timestamp: admin.firestore.Timestamp.now()
}).then(result => {
console.log("Message sent")
}).catch(err => {
console.log("Error sending mesage:", err)
})
})
As explained in the documentation of the HTTP Callable Cloud Functions:
To return data after an asynchronous operation, return a promise.
Then follows an example:
const sanitizedMessage = sanitizer.sanitizeText(text); // Sanitize the message.
return admin.database().ref('/messages').push({
text: sanitizedMessage,
author: { uid, name, picture, email },
}).then(() => {
console.log('New Message written');
// Returning the sanitized message to the client.
return { text: sanitizedMessage };
})
So you need to adapt your code as follows:
exports.sendMessage = functions.https.onCall((data, context) => {
if (context.auth.uid == undefined) {
console.warn("SEND MESSAGE: USER NOT SIGNED IN");
//Here send back an error as explained here: https://firebase.google.com/docs/functions/callable#handle_errors
}
console.log("Sending message:", data)
const matchId = data["matchId"];
const message = data["message"]
const uid = context.auth.uid
//Note the return on next line
return admin.firestore().collection(MatchingUsers).doc(matchId).collection(UserMessages).add({
type: "text",
from: uid,
message: message,
timestamp: admin.firestore.Timestamp.now()
}).then(result => {
console.log("Message sent");
return { text: "Message sent" };
}).catch(err => {
console.log("Error sending mesage:", err);
//Here, again, send back an error as explained here: https://firebase.google.com/docs/functions/callable#handle_errors
})
})
If you don't want to return a value to the client, you could do as follows, returning null when the Promise returned by the add() asynchronous method resolves. (Not tested but it should work).
exports.sendMessage = functions.https.onCall((data, context) => {
if (context.auth.uid == undefined) {
console.warn("SEND MESSAGE: USER NOT SIGNED IN");
return null;
}
console.log("Sending message:", data)
const matchId = data["matchId"];
const message = data["message"]
const uid = context.auth.uid
//Note the return on next line
return admin.firestore().collection(MatchingUsers).doc(matchId).collection(UserMessages).add({
type: "text",
from: uid,
message: message,
timestamp: admin.firestore.Timestamp.now()
}).then(result => {
console.log("Message sent"); //Actually, if you don't need this console.log() you can remove this entire then() block, returning the promise from add() is enough
return null;
}).catch(err => {
console.log("Error sending mesage:", err);
return null;
})
})

Firebase Cloud Functions: Cannot pass the token retrieved from Realtime Database

I'm having issues in retrieving a token saved in realtime database using cloud function's admin.database(). There is only one token to read from the child.
Firebase Database structure
Here's my code in Index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database
.ref('/Logs/{LogsID}')
.onWrite( (change, context) => {
const notificationSnapshot = change.after.val();
const status = notificationSnapshot.Status;
const time = notificationSnapshot.Time;
const payload = {
notification: {
title : status,
body : time
}
}
console.info(notificationSnapshot);
const pushToken = admin.database().ref('/Tokens').once('child_added').then( (data) => {
const tokenSnapshot = data.val();
const finaltoken = tokenSnapshot.token;
console.info(finaltoken);
})
// Need help down here.
admin.messaging().sendToDevice(finaltoken, payload)
.then( () => {
console.log('Notification sent');
})
.catch( () =>{
console.log('Notification failed');
})
return null;
});
finalToken shows the correct token in log as expected. Log Showing the token
But I'm getting error while I'm passing the same token to admin.messaging(). Console is logging 'Notification sent' but not receiving a notification.
ReferenceError: finaltoken is not defined
at exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:43:36)
at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20)
at /var/tmp/worker/worker.js:827:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
It works when I directly pass the token like,
var finalToken = 'ephrj1........kndji'
so the admin.messaging() works, only passing the token is not working.
I'm new to Cloud Functions and javascript, so any help is much appreciated.
Final token is being retrieved in callback / async function.
That means that when you add it to .sendToDevice() the token is undefined because the async function has not retrieved the token from the database... yet.
const pushToken = admin.database().ref('/Tokens').once('child_added').then( (data) => {
const tokenSnapshot = data.val();
const finaltoken = tokenSnapshot.token;
console.info(finaltoken);
admin.messaging().sendToDevice(finaltoken, payload)
.then( () => {
console.log('Notification sent');
})
.catch( () =>{
console.log('Notification failed');
})
// I moved admin.messaging above this bracket
})
// It used to be here
return null;
Try putting the admin.messaging code within the code block of (data) => {}
By doing this we ensure that whenever we call sendToDevice() the token is defined.

Resources