0
votes

i want to send users notification when they are being sent friend request using firebase cloud messaging, but when the request is sent it returns this error in firebase function log

Error: Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array. at FirebaseMessagingError.Error (native) at FirebaseMessagingError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:39:28)

this is the java-script code i am using

'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 for :', user_id);

	if (!change.after.val()){
		return console.log("A Notification Has Been Deleted From The Database: ", notification_id)
	}

	const deviceToken = admin.database().ref(`/Notifications/${user_id}/${notification_id}`).once('value');

	return deviceToken.then(result => {

		const token_id = result.val();

		const payload = {
			notification: {
				title: "Friend Request",
				body: "You just got a new friend request",
				icon: "default"
			}
		};
	
		return admin.messaging().sendToDevice(token_id, payload ).then(Response =>{
	
			console.log('this is the notification')
		});
	

	});


});
2

2 Answers

1
votes

It sounds like token_id is null or an empty string. Most likely that's because /Notifications/${user_id}/${notification_id} doesn't exist in your database, for example when there is no token for the targeted user.

To prevent the error message, simply check if the snapshot exists before using its value:

const deviceToken = admin.database().ref(`/Notifications/${user_id}/${notification_id}`).once('value');

return deviceToken.then(result => {
    if (!result.exists() || result.val() === "") return false;

    const token_id = result.val();

    const payload = {
        notification: {
            title: "Friend Request",
            body: "You just got a new friend request",
            icon: "default"
        }
    };

    return admin.messaging().sendToDevice(token_id, payload ).then(Response =>{ 
        console.log('this is the notification')
    });
});
1
votes

after many wasted hours i got to discover what was wrong. now the issue was that i was pointing to the wrong path. this line of code was the issue

const deviceToken = admin.database().ref(`/Notifications/${user_id}/${notification_id}`).once('value');

it was supposed to be this

const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');