Android:聊天的云端功能 [英] Android : Cloud function for Chat

查看:249
本文介绍了Android:聊天的云端功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难创建用于聊天功能的云端功能。我的Firebase设计如下所示:



我创建了云函数,但它不起作用,并且没有推送通知进入 receiverUid



这是我的云端功能:

  // //开始编写Firebase函数
// // https:/ /firebase.google.com/functions/write-firebase-functions
//
//导出常量helloWorld = functions.https.onRequest((request,response)=> {
/ / response.send(Hello from Firebase!);
//});
let functions = require('firebase-functions');
让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){
//如果发送者是接收者,不要发送push notif
promises.push(event.data.current.ref.remove());
返回Promise.all (promises);
}

// dokters ==医生作为接收者
//发件人是当前firebase用户
const getInstanceIdPromise = admin.database()。 ref(`/ dokters / $ {receiverUid} / instanceId`).once('value');
const getSenderUidPromise = admin.auth()。getUser(senderUid);

Promise .all([getInstanceIdPromise,getSenderUidPromise])。then(result => {
const instanceId = result [0] .val();
const sender = result [1];
console.log('通知'+ receiverUid +'关于'+ message.body +'from'+ senderUid);
$ b $常量有效载荷= {
通知:{
title:sender.displayName,
body:message.body,
icon:sender.photoURL
}
};
$ b $ admin.messaging()。sendToDevice(instanceId,payload)
.then(function(response){
console.log(Successfully sent message:,response);
})
.catch(function(error){
console.log(Error sending message:,error);
});
});
}));

我的问题是如何从上述设计中创建正确的云端功能。

解决方案

您已在 initializeApp()函数内声明了您的云功能。此功能用于初始化Firebase SDK,并且您应该将项目凭证传递给它:

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

请参阅 Admin SDK文档了解更多详细信息。

然后您声明您的云端功能:

  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){
//如果发件人是收件人,请不要发送push notif
promises.push(event.data.current.ref.remove( ));
return Promise.all(promises);
}

// dokters ==医生作为接收者
//发件人是当前的firebase用户
const getInstanceIdPromise = admin.database()。ref(`/ dokters / $ {receiverUid} / insta nceId`)。一旦(值);
const getSenderUidPromise = admin.auth()。getUser(senderUid);

return Promise.all([getInstanceIdPromise,getSenderUidPromise])。then(result => {
const instanceId = result [0] .val();
const sender =结果[1];
console.log('通知'+ receiverUid +'关于'+ message.body +'from'+ senderUid);

const payload = {
通知:{
title:sender.displayName,
body:message.body,
icon:sender.photoURL
}
};
$ b $ (函数(响应){
console.log(成功发送消息:,响应);
})
.catch(function(error){
console.log(Error sending message:,error);
});
});
});


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.

解决方案

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);
                });
        });
    });

这篇关于Android:聊天的云端功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆