我需要帮助为我的聊天应用程序创建节点js代码。当我发送朋友请求时,我应该收到通知,而当一个用户向另一用户发送消息时,我应该收到通知。如果使用消息传递,则仅当应用程序不是前台应用程序时,用户才应收到通知,否则,则不会。
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/notification/request/{user_id}/{notification_id}').onWrite((data, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification to send to : ', user_id);
const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
return deviceToken.then(result=>{
const token_id=result.val();
const payload={
notification:{
title: "Friend Request Received",
body: "You have received a friend request",
icon:"default"}
};
return admin.messaging().sendToDevice(token_id,payload).then(response =>{
console.log('This was notification feature');
return true;});
});
});
如果我可以添加上面相同的行,但是使用不同的路径(例如我的上面的路径),那么我已经创建了一个数据库,用于在通知中存储请求和消息,因此,如果有请求,则此代码将运行,并且用于向消息发送具有不同路径的代码。
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/notification/message/{user_id}/{notification_id}').onCreate((data, context) => {
const uid = context.params.uid;
const user_id = context.params.user_id;
const push_id = context.params.push_id;
console.log('We have a notification to send to : ', user_id);
const message = admin.database().ref(`/notification/request/${user_id}/${notification_id}/message`).once('value');
const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
return deviceToken.then(result=>{
const token_id=result.val();
const payload={
notification:{
title: "Message Received From:"+user_id,
body: message,
icon:"default"}
};
return admin.messaging().sendToDevice(token_id,payload).then(response =>{
console.log('This was notification feature');
return true;});
});
});
像一个函数一样,我可以同时使用index.js文件中的代码。我对这个东西还是陌生的,不是一个好的编码员,所以如果有人可以帮助的话。先感谢您。