Ошибка генерации Firebase Cloud Messaging - PullRequest
0 голосов
/ 11 июля 2019

Я пытаюсь вызвать push-уведомление всякий раз, когда в поле документа записывается. Поскольку я новичок в node.js, мне трудно отладить эту, казалось бы, простую функцию. Вот мой код:

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.firestore.document("Customer_Data/{userEmail}/Placed_Orders/{orderId}/status").onWrite(event => {
  const userEmail = event.params.userEmail;

  const message = "Your meal will be delivered in 2 hours";
  const title = "Eat Away";

  const toUser = admin.firestore().collection("Customer_Data").doc(userEmail).get();

  return admin.firestore().collection("Customer_Data").doc({userEmail}).get().then(queryResult => {
    const tokenId = queryResult.data().tokenId;

    const notificationContent = {
      notification: {
        title: title,
        body: message,
      }
    }
  });

  return admin.messaging().sendToDevice(tokenId , notificationContent).then(function(response) {
    console.log("Message sent successfully");
  }).catch(function(error){
    console.log("Error sending message:", error);
  });

});

И вот ошибка, которую я получаю в терминале:

 53:11  warning  Avoid nesting promises                      promise/no-nesting
  53:11  warning  Avoid nesting promises                      promise/no-nesting
  53:77  warning  Unexpected function expression              prefer-arrow-callback
  53:77  error    Each then() should return a value or throw  promise/always-return
  55:13  warning  Unexpected function expression              prefer-arrow-callback

✖ 5 problems (1 error, 4 warnings)
  0 errors and 2 warnings potentially fixable with the `--fix` option.

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.

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

Я не использовал обещание, потому что не видел в этом смысла. Но в то же время я попробовал, и это не помогло.

1 Ответ

0 голосов
/ 12 июля 2019

Отсутствие смысла в обещаниях обычно является причиной узнать о них больше, а не не использовать их.

То, как вы сейчас написали свой код, означает, что часть его никогда не выполняется.Это пока не имеет ничего общего с обещаниями, а просто с тем фактом, что у вас есть два оператора возврата в основном потоке вашего кода:

exports.sendNotification = functions.firestore.document("Customer_Data/{userEmail}/Placed_Orders/{orderId}/status").onWrite(event => {
  ...
  return admin.firestore().collection("Customer_Data").doc({userEmail}).get().then(queryResult => {
    ...
  });

  // Nothing below this line ever executes
  return admin.messaging().sendToDevice(tokenId , notificationContent).then(function(response) {
    console.log("Message sent successfully");
  }).catch(function(error){
    console.log("Error sending message:", error);
  });
});

В этом случае вам нужны результаты из Firestore для отправкисообщение FCM, означающее, что вам нужно дождаться разрешения обещания Firestore (с then() или await), прежде чем вызывать FCM:

exports.sendNotification = functions.firestore.document("Customer_Data/{userEmail}/Placed_Orders/{orderId}/status").onWrite(event => {
  const userEmail = event.params.userEmail;

  const message = "Your meal will be delivered in 2 hours";
  const title = "Eat Away";

  const toUser = admin.firestore().collection("Customer_Data").doc(userEmail).get();

  return admin.firestore().collection("Customer_Data").doc({userEmail}).get().then(queryResult => {
    const tokenId = queryResult.data().tokenId;

    notificationContent = {
      notification: {
        title: title,
        body: message,
      }
    }

    return admin.messaging().sendToDevice(tokenId , notificationContent);
  })
});
...