Reputation: 566
I am trying to create a push notification with firebase cloud functions. Following is my code:
const admin = firebase
exports.sendNewTripNotification = functions.firestore
.document('notifications/{notificationId}')
.onWrite(async (event) => {
console.log("event: ", event)
const key = "cK0e5ZRAVRUAlx8hXHkNkXp7mj43"
const ref = admin.database().ref(`users/${key}/deviceToken`);
console.log("ref: ", ref)
const deviceToken = admin.database().ref(`/users/${key}/deviceToken`).once('value');
return deviceToken.then(result => {
const token_id = result.val();
console.log("token_id", token_id)
const payload = {
notification: {
title: "Friend Request",
body: "You just got a new friend request",
icon: "default"
}
};
console.log("payload", payload)
return admin.messaging().sendToDevice(token_id, payload).then(Response => {
console.log('this is the notification',Response)
});
});
})
I'm getting the following error:
Error: Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array. at FirebaseMessagingError.FirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:42:28) at FirebaseMessagingError.PrefixedFirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:88:28)
I did consult the following two links but got no help. Am I doing anything wrong here?
Firebase Cloud Functions get data on real time database onCreate
Firebase Cloud Functions Tokens
Upvotes: 0
Views: 738
Reputation: 566
The issue has been fixed. I was doing a silly mistake. I wasn't overwriting device token on login in another device.
Upvotes: 0
Reputation: 83181
You are mixing the use of async/await with then()
, which is not recommended. The following should do the trick (untested):
exports.sendNewTripNotification = functions.firestore
.document('notifications/{notificationId}')
.onWrite(async (event) => {
console.log("event: ", event)
const key = "cK0e5ZRAVRUAlx8hXHkNkXp7mj43"
const ref = admin.database().ref(`users/${key}/deviceToken`);
console.log("ref: ", ref)
const deviceToken = await ref.once('value');
const token_id = deviceToken.val();
console.log("token_id", token_id)
const payload = {
notification: {
title: "Friend Request",
body: "You just got a new friend request",
icon: "default"
}
};
const messagingDevicesResponse = await admin.messaging().sendToDevice(token_id, payload);
console.log('this is the notification', messagingDevicesResponse)
return null;
})
Upvotes: 0