Hi this is the code that I want too use to send friend request notification from one app to other android app.
but I am getting Function returned undefined
, expected Promise or value
error in functions console and also I am not getting the token value..
My code is below...
'use-strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
exports.sendNotification = functions.firestore
.document("users/{user_id}/notifications/{notification_id}")
.onWrite((change,context)=>{
const user_id = context.params.user_id;
console.log("We have a notification to send to", user_id);
var ref = db.collection('device_token').doc(user_id);
var getDoc = cityRef.get().then(doc=>{
if (!doc.exists) {
return console.log('No such document!');
} else {
console.log('Document data:', doc.data());
const payload = {
notification: {
title: "Text.",
body: "You have a new Friend Request!",
icon: "default"
}
}
return admin.messaging().sendToDevice(tockenDoc, payload).then(response=>{
return console.log("Notification sent : success");
});
}
}).catch(err=>{
console.log('Error getting document', err);
});
});
Functions that are triggered by background operations (such as the write to Firestore in your case) and that execute asynchronous operations (such as the write to
sendToDevice()
in your code), need to return either a value or a promise to make it clear when they are done. You're not returning anything, so Cloud Functions complains that it doesn't know when the code is done.Since you're not using the
getDoc
variable anywhere, you might as well return that. Thereturn admin.messaging().sendToDevice()
from within there will bubble up, and give Cloud Functions the information it needs to know how long to keep your function's container alive.onWrite
create one Promise, that Promise stored togetDoc
,You can return
getDoc
.