I am trying to write a new key to every existing UID when a new notification sent.
The code works like this; When a new message is written to realtime database a new notification is sent to every device.
So far it works in my code.
But I want to write to the existing UID's, a new entry for notification count badge in my android app to show unread count.
EDIT: Problem is solved. See next code block.
Here is my code:
import * as functions from 'firebase-functions';
const admin = require("firebase-admin");
admin.initializeApp();
/** NOTIFICATIONS */
exports.sendNotification = functions.database.ref('/notifications/{pushId}')
.onCreate((snapshot, context) => {
const notification = snapshot.val();
const title = notification.title;
const topic = 'notifications';
const message = {
data: {
title: notification.title,
body: notification.message,
link: notification.link,
},
topic: topic
};
// Send a message to devices subscribed to the provided topic.
admin.messaging().send(message)
.then((response: String) => {
// Response is a message ID string.
console.log('Successfully sent message: ', response);
writeBadge()
})
.catch((error: String) => {
console.log('Error sending message: ', error);
});
return null;
});
// The problem is in this function
function writeBadge() {
return admin.database().ref('/users').once('value').then(function (snapshot) {
snapshot.forEach((userSnapshot => {
const uid = userSnapshot.key;
const myRef = admin.database().ref("/users/" + uid + "/badge").push();
const key = myRef.key;
userSnapshot.child("badge/" + key).set({
key: true
});
console.log('Pushed UID: ' + uid);
}));
});
}
This is the answer I was looking. This works for me.
function writeBadge() {
return admin.database().ref('/users').once('value').then(function (snapshot) {
snapshot.forEach((userSnapshot => {
const uid = userSnapshot.key;
const myRef = admin.database().ref("/users/" + uid + "/badge").push();
myRef.set({
key: true
});
console.log('Pushed UID: ' + uid);
}));
});
}