Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

node.js - Android : Cloud function for Chat

I face a difficulty to create the Cloud Function for chatting feature. My firebase design look like the follows : enter image description here

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...