Hi I am getting this lint error 'error Missing JSDoc comment require-jsdoc' in my index .js file when doing firebase deploy. Can anyone help?
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.announceProduct = functions.database
.ref("/products/{productID}")
.onCreate((event) => {
const product = event.val();
sendNotification(product);
return event.ref.set(product);
});
function sendNotification(product) {
const title = product.title;
const cost = product.cost;
const payload = {
notification: {
title: "New Product Available",
body: title + " for £ " + cost,
sound: "default",
},
};
console.log(payload);
const topic = "newProducts";
admin.messaging().sendToTopic(topic, payload);
}
Thanks :-)
Related
I'm trying to deploy a function to send notifications for my chat application. I get this error shown below, but I can't understand where the it comes from.
Could you help me to understand where the error comes from? Is this a problem with my code in the index.js file?
Here is the error:
index.js :
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.notifyNewMessage = functions.firestore
.document('notifications/{uId}/messages/{messageId}')
.onCreate( async (docSnapshot, context) => {
//************************************Obtener datos de la notificacion
const messageNotification = docSnapshot.data();
////////////extraemos los datos
const uidAuthor = messageNotification['uidAuthor'];
const uidReceiver = messageNotification['uidReceiver'];
const messages = messageNotification['message'];
const typeNotification = messageNotification['type'];
//************************************DECLARAR PROMESAS
const getAuthorData = admin.firestore().doc('users/' + uidAuthor).get();
const getReceiverData = admin.firestore().doc('users/' + uidReceiver).get();
//************************************
const results = await Promise.all([getAuthorData, getReceiverData]);
//************************************
const author = results[0];
const receiver = results[1];
//************************************GET DATA USER AUTHOR
const name = author.get('name');
//************************************GET DATA USER RECEIVER
const tokenNotification = receiver.get('tokenNotification');
//console.log("Datos recogidos USER TO NOTIFY:TOKENS " + tokens);
//////////////////////////////////NOTIFICATION DATA
payload = {
data: {
typeNotif: typeNotification.toString(),
userName: name,
userID: uidAuthor,
message: messages
}
};
admin.messaging().sendToDevice(tokenNotification, payload)
.then(function(response) {
return response;
})
.catch(function(error) {
return error;
});
//////////////////////////////////
});
firebase.js:
{
"functions": {
"predeploy": [
"npm --prefix functions run lint"
]
}
}
I am currently learning firebase cloud functions and firebase cloud messaging so I am fairly new to cloud functions and FCM on the web. How can I be able to receive a notification payload from a cloud function and display that notification on the web page? I would like to utilise Firebase Cloud Messaging to do so. So far the documents are kind of confusing for me. The website is using Javascript. The code of the cloud function is below:
'use-strict'
const functions = require('firebase-functions');
const admin = require ('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.firestore.document("Employee_Details/{user_id}/Notifications/{notification_id}")
.onWrite((change , context) =>{
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
//console.log("User ID:" + user_id + "| Notification ID : " + notification_id);
return admin.firestore().collection("Employee_Details").doc(user_id)
.collection("Notifications").doc(notification_id).get().then(queryResult => {
const from_user_id = queryResult.data().from;
const from_description = queryResult.data().description;
const from_incident = queryResult.data().incident;
const receiver_id = queryResult.data().myId;
const from_data = admin.firestore().collection("Employee_Details").doc(from_user_id).get();
const to_data = admin.firestore().collection("Employee_Details").doc(user_id).get();
// console.log("FROM_DAT:" + from_data + "TO_DATA:" + to_data);
return Promise.all([from_data , to_data]).then(result => {
const from_name = result[0].data().first_name;
const to_name = result[1].data().first_name;
const token_id = result[1].data().token_id;
const payload = {
notification: {
title:"Notification from :" + from_name,
body :from_incident + ":" +from_description,
icon : "default",
},
data:{
message: from_description,
from_user_id : from_user_id,
receiver_id : receiver_id
}
};
return admin.messaging().sendToDevice(token_id , payload).then(reuslt =>{
return console.log("Notification sent.");
});
});
});
});
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
I'm currently using Firebase Functions to send automatic push notifications when the database is uploaded. It's working perfectly, I'm just wondering how I can get a specific value from my database, for example PostTitle and display it on, for example title.
In Firebase my database is /post/(postId)/PostTitle
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// database tree
exports.sendPushNotification = functions.database.ref('/posts/{id}').onWrite(event =>{
const payload = {
notification: {
title: 'This is the title.',
body: 'There is a new post available.',
badge: '0',
sound: 'default',
}
};
return admin.database().ref('fcmToken').once('value').then(allToken => {
if (allToken.val()){
const token = Object.keys(allToken.val());
console.log(`token? ${token}`);
return admin.messaging().sendToDevice(token, payload).then(response =>{
return null;
});
}
return null;
});
});
If I understand correctly that you want to get the PostTitle from the node that triggers the Cloud Function, the following should do the trick:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// database tree
exports.sendPushNotification = functions.database.ref('/posts/{id}').onWrite(event =>{
const afterData = event.data.val();
const postTitle = afterData.PostTitle; //You get the value of PostTitle
const payload = {
notification: {
title: postTitle, //You then use this value in your payload
body: 'There is a new post available.',
badge: '0',
sound: 'default',
}
};
return admin.database().ref('fcmToken').once('value').then(allToken => {
if (allToken.val()){
const token = Object.keys(allToken.val());
console.log(`token? ${token}`);
return admin.messaging().sendToDevice(token, payload)
} else {
throw new Error('error message to adapt');
}
})
.catch(err => {
console.error('ERROR:', err);
return false;
});
});
Note the following points:
You are using the old syntax for Cloud Functions, i.e. the one of versions <= v0.9.1. You should migrate to the new version and syntax, as explained here: https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database
I have re-organised your promise chaining and also added a catch() at the end of the chain.
I'd use ...
var postTitle = event.data.child("PostTitle").val;
while possibly checking, it the title even has a value
... before sending out any notifications.
I don't know how to send different types of notification to the device from Firebase cloud function in index.js I want to send (comments notification)(like notification).
I am using this code to get following notification to device but I don't know how to get other.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/notification/{user_id}/{notification_id}').onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification to send to : ', user_id);
const fromUser = admin.database().ref(`/notification/${user_id}/${notification_id}`).once('value');
return fromUser.then(fromUserResult => {
const from_user_id = fromUserResult.val().from;
const from_message = fromUserResult.val().message;
console.log('You have new notification from : ', from_user_id);
const userQuery = admin.database().ref(`users/${from_user_id}/username`).once('value');
const deviceToken = admin.database().ref(`users/${user_id}/device_token`).once('value');
return Promise.all([userQuery,deviceToken]).then(result =>{
const userName = result[0].val();
const token_id = result[1].val();
const payload1 = {
notification:{
title: "some is following you",
body: `${userName} is following you`,
icon: "default",
click_action : "alpha.noname_TARGET_NOTFICATION"
},
data:{
from_user_id:from_user_id
}
};
return admin.messaging().sendToDevice(token_id, payload1).then(result=>{
console.log("notification sent");
});
})
.then(response => {
console.log('This was the notification Feature');
return true;
}).catch(error => {
console.log(error);
//response.status(500).send(error);
//any other error treatment
});
});
});
You can change what you are sending to the /notification/${user_id}/${notification_id} node to include fields that will let you identify and create different notifications in the cloud function.
For example, you could add a type field and then:
return fromUser.then(fromUserResult => {
const from_user_id = fromUserResult.val().from;
const from_message = fromUserResult.val().message;
const from_type = fromUserResult.val().type;
Then you could build your notification based on type:
if(from_type === NOTIFICATION_FOLLOW){
payload1 = {
notification:{
title: "some is following you",
body: `${userName} is following you`,
icon: "default",
click_action : "alpha.noname_TARGET_NOTFICATION"
},
data:{
from_user_id:from_user_id
}
};
}else{
//set payload1 for a different notification
}
Add whatever fields are necessary for your payload and extend the control structure as needed.
I have tried Firebase cloud function for sending a notification.My project structure
and this is the index.js,
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.pushNotification = functions.database.ref('/messages').onWrite( event => {
console.log('Push notification event triggered');
const message = event.data.val();
const user = event.data.val();
console.log(message);
console.log(user);
const topic = "myTopic";
const payload = {
"data": {
"title": "New Message from " + user,
"detail":message,
}
};
return admin.messaging().sendToTopic(topic, payload);
});
The above code is misconfigured, when I deploy in Node.js, LOG in Function shows:
"TypeError: Cannot read property 'val' of undefined".
What Actually I am trying to do :
I am trying to extract info from snapshot load into that index.js so that when a new child gets added to Real-time database, it should trigger a notification payload with a title and body.
In Android, I use a child listener, for listening when a new record is added
FirebaseDatabase.getInstance().getReference().child("messages")
OnChildAdded(.....){
if (dataSnapshot != null) {
MessageModel messageModel = dataSnapshot.getValue(MessageModel.class);
if (messageModel != null) {
// do whatever
}
}
But in index.js, I could not able to parse that.
A bit guidance how to fixate index.js according to my database structure would be immensely appreciated.
PS- I have never done coding in JS
If you want more context, I'd be happy to provide it.
Change this:
exports.pushNotification = functions.database.ref('/messages').onWrite( event => {
const message = event.data.val();
const user = event.data.val();
});
to this:
exports.pushNotification = functions.database.ref('/messages').onWrite(( change,context) => {
const message = change.after.val();
});
Please check this:
https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database
The cloud functions were changed and now onWrite has two parameters change and context
The change has two properties before and after and each of these is a DataSnapshot with the methods listed here:
https://firebase.google.com/docs/reference/admin/node/admin.database.DataSnapshot
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/NOTIFICATIONS/{UserId}/{{notification_id}').onWrite((change, context) =>
{
const UserId = context.params.UserId;
const notification = context.params.notification;
console.log('The user Id is : ', UserId);
if(!change.after.exists())
{
return console.log('A Notification has been deleted from the database : ', notification_id);
}
if (!change.after.exists())
{
return console.log('A notification has been deleted from the database:', notification);
return null;
}
const deviceToken = admin.database().ref(`/USER/${UserId}/device_token`).once('value');
return deviceToken.then(result =>
{
const token_id = result.val();
const payload = {
notification : {
title : "Friend Request",
body : "You've received a new Friend Request",
icon : "default"
}
};
return admin.messaging().sendToDevice(token_id, payload).then(response => {
console.log('This was the notification Feature');
});
});
});