I have not more experience of Android and almost have no idea in javascript coding, I followed a tutorial to create a firebase function and now firebase function change beta to stable and my code is showing me error :
this is my code --->
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref('/notifications/{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 from : ', user_id);
if (!event.data.exists()) {
return console.log('A Notification has been deleted from the database : ', notification_id);
}
const fromUser = admin.database().ref(`/notifications/${user_id}/${notification_id}`).once('value');
return fromUser.then(fromUserResult => {
const from_user_id = fromUserResult.val().from;
console.log('You have new notification from : ', from_user_id);
const userQuery = admin.database().ref(`Users/${from_user_id}/name`).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 payload = {
notification: {
title : "New Friend Request",
body: `${userName} has sent you request`,
icon: "default",
click_action : "in.tvac.akshaye.lapitchat_TARGET_NOTIFICATION"
},
data : {
from_user_id : from_user_id
}
};
return admin.messaging().sendToDevice(token_id, payload).then(response => {
console.log('This was the notification Feature');
});
});
});
});
and this is my database ---->
notifications
BOhvOUJG8sWgIyTD7JLuSOgfv9v1
aqTdCWJYfvQiw188MqldsDtlLFf2
-LLO14ghpMruZtqwK7CR from: "rrajSiL7SFd7WQydkA7jwxi26s63" type: "request"
-LLOQ2WsWHymJvdOxrx5 from: "rrajSiL7SFd7WQydkA7jwxi26s63" type: "request"
-LLfVM43o8Rt-1A55r28
-LLfxudlktvk3ysxvype
i am getting this error --->
ReferenceError: event is not defined
at exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:15:7)
at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20)
at /var/tmp/worker/worker.js:733:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Please check if you have defined the event or not
Related
I wrote a node.js function which sends notification on to an Android device by payload. I've deployed the index.js(file that content the function) on to Firebase Cloud Messaging.
After sending a message the log shows that the notification is sent at the same time it shows error, and I'm not able to receive notification on targeted device.
Here's my index.js file that content the function:
'use-strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.firestore.document("Users/{user_id}/notifMessages/{notification_id}").onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
return admin.firestore().collection("Users").doc(user_id).collection("notifMessages").doc(notification_id).get().then(queryResult => {
const from_user_id = queryResult.data().fromUser;
const from_message = queryResult.data().message;
const from_data = admin.firestore().collection("Users").doc(from_user_id).get();
const to_data = admin.firestore().collection("Users").doc(user_id).get();
return Promise.all([from_data, to_data]).then(result => {
const from_name = result[0].data().nom;
const to_name = result[1].data().nom;
const tokenId = result[1].data().tokenId;
const payload = {
notification: {
title : "Notification from : "+from_name,
body : from_message,
icon : "default",
click_action: "mr.pharma_proche.TARGETNOTIFICATION"
},
data: {
message : from_message,
from_user_id : from_user_id
}
};
return admin.messaging().sendToDevice(tokenId, payload).then(result => {
console.log("Notification sent : "+from_name+" to : "+to_name+" Token : "+tokenId);
return results;
}).catch((error) => {
console.log("error, message not sent");
});
});
});
});
I'm trying to do a simple notification function
but every time i fire the function i get ERROR
TypeError: Cannot read property 'params' of undefined
at exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:23:32)
at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20)
at /var/tmp/worker/worker.js:758:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Or i get the error
TypeError: Cannot read property 'user_id' of undefined
I got an answer from here
but i't didn't help at all , and i can't find the problem . this is my code
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change,context) => {
const user_id = event.params.user_id;
const notification_id = event.params.notification_id;
console.log('We have a notification from : ', user_id);
if(!context.data.val()){
return console.log('A Notification has been deleted from the database : ',
notification_id);
}
const fromUser =admin.database().ref(`/notifications/${user_id}/${notification_id}`).once('value');
return fromUser.then(fromUserResult => {
const from_user_id = fromUserResult.val().from;
console.log('You have new notification from : ', from_user_id);
const userQuery = admin.database().ref(`Users/${from_user_id}/name`).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 payload = {
notification: {
title : "New Friend Request",
body: `${userName} has sent you request`,
icon: "default",
click_action : "none"
},
data : {
from_user_id : from_user_id
}
};
return admin.messaging().sendToDevice(token_id, payload).then(response => {
return console.log('This was the notification Feature');
});
});
});
});
You never defined event, so it's undefined. You're trying to access a property on an undefined variable. Did you mean context.params.user_id?
(You're probably using an out of date tutorial. I see bad "sendNotification" functions like this all the time on Stack Overflow. Let the author know.)
My application is simply order app and I want admin get notification when new order is placed.
So to do that I send notification to device with token Id by using firebase functions.
'use-strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('admin/{user_id}/notification/{notification_id}').onCreate((snapshot, context) => {
console.log("hehehehehehehehe");
const user_id=context.params.user_id;
const getDeviceTokensPromise = admin.database().ref(`admin/${user_id}`).once('value');
//let tokensSnapshot;
//let tokes;
return Promise.all([getDeviceTokensPromise]).then(result => {
//const registrationToken= result[0].tokenid.val();
//console.log(registrationToken);
const payload = {
notification: {
title: 'You have a new follower!',
body: 'Yeni sifaris var',
}
};
return admin.messaging().sendToDevice('fOCU86Rhhb4:APA91bHwJZInZYGp9cIDc7PyCw48QcEvvMOMuFepYcCTvkxlCJp8_Ieq1Ikwd9xNoU2rfTA9paRqCTLAuhUlZgF952AvpBstGdGRWMK8lCR2MHgHn6xzbvyxFEu-auRYexnPYmOnlTB1',payload).then((response) => {
return console.log('Successfully sent message:', response);
}).catch((error) => {
return console.log('Error sending message:', error);
});
});
});
Although I got the success response message in console log, my android phone couldn't get any notification.
Successfully sent message: { results: [ { messageId: '0:1542910779596746%095eb9af095eb9af' } ],
canonicalRegistrationTokenCount: 0,
failureCount: 0,
successCount: 1,
multicastId: 6551370257673400000 }
What is wrong with my code. I am new to firebase. I need your help.
This question already has answers here:
Firebase functions how to send a notification in Android
(1 answer)
Firebase functions: cannot read property 'user_id' of undefined
(1 answer)
Firebase cloud functions stopped working - event.data undefined
(2 answers)
node js function onWrite is not working properly in google cloud function
(1 answer)
Closed 4 years ago.
I'm working with Notifications but the Notification is not working and getting this error, I am new to this so i can't fully understand this and getting tilted by the error. Any help would be appreciated, I don't find any related solutions about this
ReferenceError: event is not defined
at exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:9:31)
at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20)
at /var/tmp/worker/worker.js:744:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
and Here is my index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification =
functions.database.ref('/notifications/{user_id}/{notification_id}')
.onWrite((change, context) => {
const user_id = event.params.user_id;
const notification = event.params.notification;
console.log('We have a notification to send to: ', user_id);
if(!event.data.val())
{
return console.log('A Notification has been deleted from database: ', notification_id);
}
const fromUser = admin.database().ref(`/notifications/${user_id}/${notification_id}`);
return fromUser.then(fromUserResult => {
const from_user_id = fromUserResult.val().from;
console.log('You have new Notification from: ', from_user_id);
const userQuery = admin.database().ref(`Users/${from_user_id}/name`).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 payload = {
notification: {
title: "Message Request",
body: `${userName} has sent you a Message Request`,
icon: "logo.png",
click_action: "com.example.gab.quadrantms_TARGET_NOTIFICATION"
},
data : {
from_user_id : from_user_id
}
};
return admin.messaging().sendtoDevice(token_id, payload).then(response =>{
console.log('This was the Notification Feature');
return true;
});
});
});
});
Just as the error says, event isn't defined anywhere. It looks like you should be using context instead.
const user_id = context.params.user_id;
const notification = context.params.notification;
Here are the docs for EventContext: https://firebase.google.com/docs/reference/functions/functions.EventContext
And RefBuilder.onWrite: https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder#onWrite
Below code is my firebase function index.js file
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref("Notifications/{userId}")
.onWrite(event => {
var request = event.data.val();
var payload = {
data: {
title: "Welcome to ChitChat Group",
message: "You may have new messages"
}
};
admin.messaging().sendToDevice(request.token, payload)
.then(function (response) {
console.log("Successfully sent message: ", response);
})
.catch(function (error) {
console.log("Error sending message: ", error);
})
});
below code contains where i crate token when user get registered
String uid = (String) firebaseAuth.getCurrentUser().getUid();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications/"+uid);
reference.child("token").setValue(FirebaseInstanceId.getInstance().getToken());
You can make all your users subscribe to one big topic like registration on newMembers then send notification to the topic :
var message = {
to: '/topics/newMembers',
notification: {
title: 'title',
body: 'body'
},
};