I face a difficulty to create the Cloud Function for chatting feature. My firebase design look like the follows :
I have created the cloud function
, but it doesn't work and no push notification coming to receiverUid
.
Here is my Cloud Function :
// // Start writing Firebase Functions
// // https://firebase.google.com/functions/write-firebase-functions
//
// export const helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
let functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp(functions.database.ref('/chat_rooms/{pushId}')
.onWrite(event=>{
const message = event.data.current.val();
const senderUid = message.from;
const receiverUid = message.to;
const promises = [];
if(senderUid==receiverUid){
//if sender is receiver, don't send push notif
promises.push(event.data.current.ref.remove());
return Promise.all(promises);
}
//dokters == doctors as the receiver
// sender is current firebase user
const getInstanceIdPromise = admin.database().ref(`/dokters/${receiverUid}/instanceId`).once('value');
const getSenderUidPromise = admin.auth().getUser(senderUid);
return Promise.all([getInstanceIdPromise, getSenderUidPromise]).then(result=>{
const instanceId = result[0].val();
const sender = result[1];
console.log('notifying ' + receiverUid + ' about ' + message.body + ' from ' + senderUid);
const payload = {
notification:{
title: sender.displayName,
body: message.body,
icon: sender.photoURL
}
};
admin.messaging().sendToDevice(instanceId, payload)
.then(function (response) {
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
}));
My Question is how to create the right Cloud Function from the above design.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…