我正在尝试编写一个云函数,如果添加了另一个数据库条目,它将向我数据库中的所有设备发送推送通知
细目是...
我的用户数据库的结构是这样的-任何帮助或指向正确方向的信息都将不胜感激,因为我仍在学习整个过程。
myFirestoreRealTimeDatabase
|--messages
|------fjdhfsjkf(**Unquiqe Message id**)
|------------message: Test Push Notification
|
|--users
|------EIDdxqEkm6YVRqV3p1x9FDXuX4C2 (**Unquiqe user id**)
|------------email: myemail@email.com
|------------expoToken: "ExponentPushToken[5jxdvMLq123JhBNBCg9gDH0w]"
|
|------JFJdjksfVRqV3p1x9FDXJFJS (**Unquiqe user id**)
|------------email: myemail2@email.com
|------------expoToken: "ExponentPushToken[34jxdfdgkdsjBCg9gDH0w]"
因此,我需要在创建新的expoToken
时向所有message
发送通知
然后需要运行一个功能以使用expos push服务器,像这样。
.then((messages) => {
// console.log(messages)
fetch("https://exp.host/--/api/v2/push/send", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(messages),
});
})
这是我已经开始的代码,但是它不起作用。
const functions = require('firebase-functions');
var fetch = require('node-fetch')
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPushNotification = functions.database.ref('contacts/').onCreate(event => {
const root = event.data.ref.root
var messages = []
//return the main promise
return root.child('/users').once('value').then(function (snapshot) {
snapshot.forEach(function (childSnapshot) {
var expoPushToken = childSnapshot.val().expoPushToken;
console.log(expoPushToken);
messages.push({
"to": expoPushToken,
"sound": "default",
"body": "New Note Added"
});
});
//firebase.database then() respved a single promise that resolves
//once all the messages have been resolved
return Promise.all(messages)
})
.then(messages => {
// console.log(messages)
fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(messages)
});
})
.catch(reason => {
console.log(reason)
})
});