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
Related
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.
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
I'm trying to implement push notification using firebase in my project but not being able to do so.Below is my index.js file, i have very little knowledge about javascript and nodejs and thats why not being able to figure out the problem.
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref('/Notifications/{receiver_id}/{notification_id}').onWrite((data,context) =>
{
const receiver_id = context.params.receiver_id;
const notification_id = context.params.notification_id;
console.log('We have new notification to send to : ', receiver_id);
/*if(!context.data.val()){
return console.log('A notification has been deleted from the databse : ', notification_id);
}*/
const deviceToken = admin.database().ref(`Users/${receiver_id}/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');
return true;
});
});
});
Can anyone please explain me this code and help out with my problem.
Every device has a different token. Seems you are storing only one token for one user. That's why you can send the notification to only one device. If you want to send it to multiple devices you have to store multiple device tokens and send the notification to all those devices.
I'm working with Firebase notifications using node.js.
After compile, when I'm sending request to other user of app (request makes notification), firebase log shows error:
TypeError: Cannot read property 'receiver_id' of undefined
at exports.sendNotification.functions.database.ref.onWrite.event (/user_code/index.js:12:36)
at Object. (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:700:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Index.js code:
'use strict'
const functions = require('firebase-functions');
const admin = require ('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification =
functions.database.ref('/Notifications/{receiver_id}/{notification_id}')
.onWrite(event =>
{
const receiver_id = event.params.receiver_id;
const notification_id = event.params.notification_id;
console.log('We have a notification to send to :', receiver_id);
if(!event.data.val())
{
return console.log('A notification has been deleted from the database: ', notification_id);
}
const deviceToken = admin.database().ref(`/Users/${receiver_id}/device_token`).once('value');
return deviceToken.then(result =>
{
const token_id = result.val();
const payload =
{
notification:
{
title: "Friend Request",
body: "you have received a new friend request",
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id, payload)
.then(response =>
{
console.log('This was the notification feature.');
});
});
});
I have read about new APIs on site:
https://firebase.google.com/docs/functions/beta-v1-diff
I think I must change event to context, but I don't know how.
Is anybody know what's the issue?
Thank's for any Help :)
The Firebase documentation on the new data and context shows where the params now live:
The context parameter provides information about the function's execution. Identical across asynchronous functions types, context contains the fields eventId, timestamp, eventType, resource, and params.
So to get rid of that error, you'll need to change the first bit of your function to:
exports.sendNotification =
functions.database.ref('/Notifications/{receiver_id}/{notification_id}')
.onWrite((data, context) =>
{
const receiver_id = context.params.receiver_id;
const notification_id = context.params.notification_id;
...
There are more, similar changes that you'll need to make. If you're having a hard time making those yourself, I recommend you check back in with where you got the code from.