Reputation: 79
Seeing this tutorial on https://www.youtube.com/watch?v=R2D6J10fhA4, I am trying to implement Send Push Notifications ( Expo + Firebase Cloud Functions)
I'm trying to write a cloud function that will send a push notification to all devices in my database if another database entry is added
the breakdown is...
My user database is structured like this - any help or point in the right directions would be greatly appreciated, as I am still learning the whole thing.
myFirestoreRealTimeDatabase
|--messages
|------fjdhfsjkf(**Unquiqe Message id**)
|------------message: Test Push Notification
|
|--users
|------EIDdxqEkm6YVRqV3p1x9FDXuX4C2 (**Unquiqe user id**)
|------------email: [email protected]
|------------expoToken: "ExponentPushToken[5jxdvMLq123JhBNBCg9gDH0w]"
|
|------JFJdjksfVRqV3p1x9FDXJFJS (**Unquiqe user id**)
|------------email: [email protected]
|------------expoToken: "ExponentPushToken[34jxdfdgkdsjBCg9gDH0w]"
So I'm needing to send a notification to all expoToken when a new message is created then that need to run a function to use expos push server, something like this.
.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),
});
})
This is the code I have started but it does not work .
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)
})
});
Upvotes: 5
Views: 2012
Reputation: 79
I made a mistake in accessing the root
instead of const root = event.data.ref.root
I should write const root = event.ref.root
Since the latest version of Firebase have changed the syntax
Upvotes: 3