I develop a web application and it needed to use push notifications, within the application and I am using Firebase for it… I can already use several of the functionalities.
Now you needed to retrieve records from the db.
This is how it sent the payload of the message
function SendNotify() {
const txt = document.getElementById('msj');
var notificationMessage = txt.value;
if (!notificationMessage) return false;
database.ref('/notifications')
.push({
user: auth.currentUser.displayName,
message: notificationMessage,
userProfileImg: auth.currentUser.photoURL,
date: date
})
.then(() => {
document.getElementById('msj').value = '';
})
.catch(() => {
console.log("error enviando");
});
txt.value = '';
}
and in the FireBase DB it looks like this:
I'm trying to try to take data from here and concatenate it to another message
I wrote this and it works but the DB fields arrive as undefined:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.Notifications = functions.database.ref('/notifications/{notificationId}')
.onWrite(async (change, context) => {
const user = context.params.user;
const message = context.params.message;
const userProfileImg = context.params.userProfileImg;
const date = context.params.date;
// Notification details.
const payload = {
notification: {
title: `Test SocialWifi de: ${user}`,
body: `Hoy: ${date} , Nuevo Mensaje ${message}`,
icons: `${userProfileImg}`,
click_action: 'https://sudokudetodos.com'
}
};
console.info(payload);
});
You should change your function trigger to
onCreate
since you are waiting for a notification to be created, if you useonWrite()
every time the document is written your function will jump, so the notification will be sent several times.If you are going to use async in the function, you should use await to fetch each value of the object being created before sending the notification, so you make sure that each value is captured before building the payload.
To get the data, snap returns the entire object with the values, we use
snap.data()
to get the value followed by the name of the attribute we want to getThe code that worked for me as recommended by Gaston Saillen is the following: