Облачные функции Firebase для Firestore не запускаются - PullRequest
0 голосов
/ 07 мая 2018

Невозможно получить облачные функции Firebase для Firestore для запуска при записи моей коллекции. Попытка настроить устройство на устройство push-уведомления для приложения чата. Функция развернута и оплачивается по мере поступления плана, однако изменения в документе, обновлениях или создании в «чатах» коллекции не инициируются. Предполагается, что облачные сообщения Firebase отправляют сообщения и записи в журнал. Ничего не происходит. Push работает с другими источниками.

Спасибо за вашу помощь, желаем, чтобы push-уведомления от устройства к устройству были проще, планируем просматривать документ чата и запускать push-уведомления при обновлении или создании нового разговора. Открыты для других идей. Спасибо

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

exports.sendNotification = functions.firestore
  .document('chats/{chatID}')
  .onWrite((data, context) => {
    // Get an object representing the document
    console.log('chat triggered');
    // perform desired operations ...

    // See documentation on defining a message payload.
    var message = {
      notification: {
        title: 'Hello World!',
        body: 'Hello World!'
      },
      topic: context.params.chatID
    };

    // Send a message to devices subscribed to the provided topic.
    return admin.messaging().send(message)
      .then((response) => {
        // Response is a message ID string.
        console.log('Successfully sent message:', response);
        return true
      })
      .catch((error) => {
        console.log('Error sending message:', error);
      });

  });

ОБНОВЛЕНИЕ: я использую "firebase-functions": "^ 1.0.1"

ОБНОВЛЕНО: обновлен код, чтобы отразить то, что мы развернули в настоящее время, все еще не работает.

Ответы [ 2 ]

0 голосов
/ 07 мая 2018

Ваш firebase-admin синтаксис инициализации , admin.initializeApp() предполагает, что вы используете Cloud Functions SDK версии 1.0.x. Параметры для onWrite() изменились в версии 1.0.x по сравнению с более ранними версиями. Вам также необходимо вернуть Promise для асинхронного действия admin.messaging.send(). Три необходимых исправления указаны ниже:

exports.sendNotification = functions.firestore
    .document('chats/{chatID}')
    .onWrite((data, context) => {  // <= CHANGE
      // Get an object representing the document
       console.log('chat triggered');
      // perform desired operations ...

        // See documentation on defining a message payload.
        var message = {
          notification: {
            title: 'Hello World!',
            body: 'Hello World!'
          },
          topic: context.params.chatID // <= CHANGE
        };

        // Send a message to devices subscribed to the provided topic.
        return admin.messaging().send(message)  // <= CHANGE
          .then((response) => {
            // Response is a message ID string.
            console.log('Successfully sent message:', response);
            return
          })
          .catch((error) => {
            console.log('Error sending message:', error);
            return
          });

});
0 голосов
/ 07 мая 2018

Есть вероятность, что вы используете старый синтаксис (до V1.0) с новой библиотекой (v1.0). См. Руководство по миграции: https://firebase.google.com/docs/functions/beta-v1-diff и проверьте версию в файле package.json.

Кроме того, обратите внимание, что облачная функция всегда должна возвращать Promise (или, если вы не можете, по крайней мере, значение, для асинхронных функций). См. Эту документацию (и связанное с ней видео), в которой это подробно объясняется: https://firebase.google.com/docs/functions/terminate-functions

Вы должны изменить свой код следующим образом:

Если вы используете Cloud Functions 1.0 или выше:

exports.sendNotification = functions.firestore
    .document('chats/{chatID}')
    .onWrite((change, context) => {

Возвращение

exports.sendNotification = functions.firestore
.document('chats/{chatID}')
.onWrite((change, context) => {
  // Get an object representing the document
   console.log('chat triggered');
  // perform desired operations ...

    // See documentation on defining a message payload.
    var message = {
      notification: {
        title: 'Hello World!',
        body: 'Hello World!'
      },
      topic: context.params.chatID.   //<- If you are using a CF version under v1.0 don't change here
    };

    // Send a message to devices subscribed to the provided topic.
    return admin.messaging().send(message).  //<- return the resulting Promise
      .then((response) => {
        // Response is a message ID string.
        console.log('Successfully sent message:', response);
        return true;    //<- return a value
      })
      .catch((error) => {
        console.log('Error sending message:', error);
        //return.  <- No need to return here
      });

});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...