Android : Cloud function for Chat

2019-09-21 02:38发布

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.

1条回答
欢心
2楼-- · 2019-09-21 03:02

You've declared your cloud function inside the initializeApp() function. This function is used to initialize the Firebase SDK, and you should pass your project's credentials to it:

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});

Refer to the Admin SDK Documentation for more details.

Then you declare your cloud function:

exports.sendNotification = 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);
                });
        });
    });
查看更多
登录 后发表回答