2

*when I try to deploy I have this error * I am new to java script .. am creating posts sharing with chat option I want to receive notification from firebase so I am using this code but there is an error while deploying please help me guys I am searching solution for this from 6hours but I didn't found

62:12  warning  Avoid nesting promises             promise/no-nesting
88:14  warning  Avoid nesting promises               promise/no-nesting
88:69  error    Each then() should return a value or throw promise/always-return

✖ 3 problems (1 error, 2 warnings)

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 likelyadditional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/alpha/.npm/_logs/2018-05-16T18_06_07_691Z-debug.log

Error: functions predeploy error: Command terminated with non-zero exit   code1

 Having trouble? Try firebase deploy --help

this is my node.js(index.js) code

'use strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

 /*
   * 'OnWrite' works as 'addValueEventListener' for android. It will fire   the function
   * everytime there is some item added, removed or changed from the provided 'database.ref'
  * 'sendNotification' is the name of the function, which can be changed according to
   * your requirement
 */



    exports.sendNotification =   functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite(event => {


 /*
  * You can store values as variables from the 'database.ref'
  * Just like here, I've done for 'user_id' and 'notification'
  */

  const user_id = event.params.user_id;
  const notification_id = event.params.notification_id;

  console.log('We have a notification from : ', user_id);

  /*
   * Stops proceeding to the rest of the function if the entry is deleted from database.
   * If you want to work with what should happen when an entry is deleted, you can replace the
   * line from "return console.log.... "
   */

  if(!event.data.val()){

 return console.log('A Notification has been deleted from the  database : ', notification_id);

 }

 /*
  * 'fromUser' query retreives the ID of the user who sent the  notification
  */

 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);

/*
 * The we run two queries at a time using Firebase 'Promise'.
 * One to get the name of the user who sent the notification
 * another one to get the devicetoken to the device we want to send notification to
 */

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();

  /*
   * We are creating a 'payload' to create a notification to be sent.
   */

  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
    }
  };

  /*
   * Then using admin.messaging() we are sending the payload notification to the token_id of
   * the device we retreived.
   */

  return admin.messaging().sendToDevice(token_id, payload).then(response => {

    console.log('This was the notification Feature');

  });

  });

 });

 });
4
  • What is this in your code ? .onWrit e(event => { Commented May 16, 2018 at 18:31
  • sorry it was mistake while cut and paste .. Commented May 16, 2018 at 18:34
  • yes please any solution Commented May 16, 2018 at 18:35
  • I have tried that also Peter Haddad Commented May 16, 2018 at 18:42

1 Answer 1

3

This code refactoring should do the trick:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

/*
  * 'OnWrite' works as 'addValueEventListener' for android. It will fire   the function
  * everytime there is some item added, removed or changed from the provided 'database.ref'
 * 'sendNotification' is the name of the function, which can be changed according to
  * your requirement
*/


exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite(event => {


    /*
     * You can store values as variables from the 'database.ref'
     * Just like here, I've done for 'user_id' and 'notification'
     */

    const user_id = event.params.user_id;
    const notification_id = event.params.notification_id;

    console.log('We have a notification from : ', user_id);

    /*
     * Stops proceeding to the rest of the function if the entry is deleted from database.
     * If you want to work with what should happen when an entry is deleted, you can replace the
     * line from "return console.log.... "
     */

    if (!event.data.val()) {

        console.log('A Notification has been deleted from the  database : ', notification_id);

        return false;
    }

    /*
     * 'fromUser' query retreives the ID of the user who sent the  notification
     */

    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);

            /*
             * The we run two queries at a time using Firebase 'Promise'.
             * One to get the name of the user who sent the notification
             * another one to get the devicetoken to the device we want to send notification to
             */

            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');
            return true;

        }).catch(error => {

          console.log(error);
          //any other error treatment
        });
});

Updated: code for version 1.0+

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;
Sign up to request clarification or add additional context in comments.

10 Comments

Note that I have modified it to add an error catch, which is mandatory. See these videos from the Firebase team: youtube.com/watch?v=7IkUgCLr5oA&t=16s and youtube.com/watch?v=652XeeKNHSk&t=8s
And one more thing: note that recently a new release of Firebase Cloud Functions occurred, with important changes in the syntax. See firebase.google.com/docs/functions/beta-v1-diff. maybe you can migrate after you have succeeded with the syntax you are using (the one for version < 1.0.0).
it deploys successfully but in log I am not able to get user_id
Cannot read property 'user_id' of undefined it is showing this in log
Which version of Cloud Functions are you using? You can see that in the package.json file under the 'dependencies' node (files is within the functions directory)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.