Reputation: 141
*Image delete
This is my firebase database, I'm trying to set up remote push messaging from events like changes or adds in Database.
I've set up so that several devices can share the same account, and each device writes a device token as a child, and stores the FCM token as a key under that child.
So the key value seen here is [FCMtoken : true]
I'm muddling my way through how to work with Javascript, here's my function that is returning null values, though I'm expecting it to return the devices FCMtoken.
exports.notificationForCommunicationAdded = functions.database.ref('/{pharmacyId}/orders/{orderId}/communications')
.onWrite(event => {
const payload = {
notification: {
title: 'New communication added',
body: 'Check it out!'
}
};
const getDeviceTokensPromise = admin.database().ref('/{pharmacyId}/userDevices/{deviceToken}').once('value');
let tokensSnapshot;
let tokens;
return getDeviceTokensPromise.then(results => {
tokensSnapshot = results;
if (!tokensSnapshot.hasChildren()) {
return console.log('There are no notification tokens to send to');
}
console.log('There are', tokensSnapshot.numChildren(), 'tokens to send to');
tokens = Object.keys(tokensSnapshot.val());
console.log('These are the tokens', tokens)
return null;
});
});
Try as I might I keep getting "null" as my return value.
Help would be much appreciated, thanks guys and gals.
Upvotes: 0
Views: 536
Reputation: 141
I finally got it working with the following syntax:
... const pharmacyId = context.params.pharmacyId;
admin.database().ref(/
+ pharmacyId + /userDevices
).once('value').then((snapshot) => {...
For some reason the syntax Doug Stevenson supplied did not work for me.
Upvotes: 0
Reputation: 317808
When you access the database, you can't do variable substitution like this:
admin.database().ref('/{pharmacyId}/userDevices/{deviceToken}')
Those curly braces are being taken literally. They don't work like the wildcards in your function definition. You'll need to build a string using the values of the wildcards using the context parameter that you're not declaring. First, you need to declare your function like this:
exports.notificationForCommunicationAdded =
functions.database.ref('/{pharmacyId}/orders/{orderId}/communications')
.onWrite((change, context) => {
Note that the first object is a Change object, and the second is a context.
Then you need to use the context to get a hold of the wildcard values:
const pharmacyId = context.params.pharmacyId
const orderId = context.params.orderId
Then you need to use those to build the path to the database:
admin.database().ref(`/${pharmacyId}/userDevices/${deviceToken}`)
Upvotes: 2