3

Javascript code for Firebase cloud functions giving errors which written for push notifications

index.js

'use strict'
//Install functions and admin sdks'
const functions = require('firebase-functions');
const admin =require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {
    //onwrite will run if data changed
    const user_id = context.params.user_id;
    const notification = context.params.notification;

    if (context.params === null) {
        return console.log("Notification Has Been Deleted");
    }
    let token_id = null;
    const deviceToken = admin.database.ref(`/Users/${user_id}/device_token`).once('value');
    return deviceToken.then(result => {

        token_id = result.val();

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


    });


    return admin.messaging().sendToDevice(token_id, payload).then(response =>{
        console.log('This is the notify feature');
    }).catch(err => {
        console.log('Error getting documents', err);
    });

});

When run firebase deploy command it is getting error as follows. I would be greateful if anyone can support.

Error

error Each then() should return a value or throw promise/always-return error Unreachable code no-unreachable error Each then() should return a value or throw promise/always-return

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: `eslint .`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.      
Community
  • 1
  • 1

5 Answers5

6

I hope it will work fine, you should return like this

return console.log('This is the notify feature');
2

The error is saying that you should return a value from the callback passed to any then() method. You have two then() methods in your code. If you have nothing to send to the next item of work in the promise chain, just return null at the end of the function.

There is an even bigger problem in your code, though. You have two return statements at the top level of your function, one right after the other. This is almost certainly going to cause another error, or at least fail to do what you expect. (You must return only one promise that resolves when all the work is complete.)

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
0

Doug Thanks for the comment. Then I changed the code. Now it is deployed without any error. But after calling the method its giving an error in the firebase functions console.(Calling the method means adding a new notification using the android app) Here in the payload, without tokens:deviceToken part also didn't work

'use strict'


//Install functions and admin sdks'
const functions = require('firebase-functions');
const admin =require('firebase-admin');
var FCM = require('fcm-push');
admin.initializeApp();


var serverKey = 'MY_SERVER_KEY_HERE';
var fcm = new FCM(serverKey);



exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {
    //onwrite will run if data changed
    const user_id = context.params.user_id;
    const notification = context.params.notification;
console.log('user : '+user_id)
console.log('notification : '+notification)
    // If exit the function.
    if (!change.after.val()) {
      return console.log('User ', user_id, 'notification', notification);
    }

// Only edit data when it is first created.
      if (change.before.exists()) {
        return null;
      }
      // Exit when the data is deleted.
      if (!change.after.exists()) {
        return null;
      }

    const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
    console.log("Dev TOken : "+deviceToken);
    return admin.database().ref(`/Users/${user_id}/device_token`).once('value').then(result => {


        const payload = {
            notification:{
                title:"Friend Request",
                body:"You have recieved a new friend request",
            },
            tokens:deviceToken
        };

        return admin.messaging().send(payload).then(response =>{
            return console.log('This is the notify feature');
        }).catch(err => {
            return console.log('Error getting documents', err);
        });
    })

});

Output:- https://i.stack.imgur.com/9ZoDp.png

Can anyone correct the code if there is any wrong?

0

Thanks All. I fixed that.

'use strict'

//Install functions and admin sdks'
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) => {
    //onwrite will run if data changed
    const user_id = context.params.user_id;
    //const from = context.params.from;
    const notification_id = context.params.notification_id;
    console.log('user : '+user_id);
    console.log('notification_id : '+notification_id);
    //console.log('notification : '+notification)
    //console.log('from : '+from)
    // If exit the function.
    if (!change.after.val()) {
      return console.log('Sender ', user_id, 'From', from);
    }

// Only edit data when it is first created.
      if (change.before.exists()) {
        return null;
      }
      // Exit when the data is deleted.
      if (!change.after.exists()) {
        return null;
      }

    // if (context.params === null) {
    //     return console.log("Notification Has Been Deleted");
    // }

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

    return getDeviceTokensPromise.then(result => {
      const payload = {
        notification: {
          title: 'You have a new follower!',
          body: `is now following you.`,
          icon: 'default'
        }
      };

      return admin.messaging().sendToDevice(result.val(), payload);

    }).then(res => {
      return console.log(JSON.stringify(res));
    });  

});
-1

For cloud function, if its https trigger then it must return a response to the user if any other type of trigger it must return a Promise. just return Promise.resolve("Done"); I have tried return null but that didn't work for me.

Shuvendu Dhal
  • 75
  • 2
  • 6