Функции Firebase - admin.messaging (). SendToTopic выполняется, но никогда не попадает в блок `then` - PullRequest
0 голосов
/ 19 сентября 2018

По какой-то причине блок then функции admin, похоже, не выполняется - я не вижу ни одного из сообщений console.log в firebase console:

Здесьвесь мой firebase functions код:

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
const firebaseHelper = require('firebase-functions-helper');
const serviceAccount = require('./serviceAccountKey.json');
var toPlainObject = require('lodash.toplainobject');

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

//firebaseHelper.firebase.initializeApp(serviceAccount, 'https://snag-b2b2d.firebaseio.com');

//if (!admin.apps.length) {
admin.initializeApp();
admin.firestore().settings({timestampsInSnapshots: true});
var db = admin.firestore();

function renameObjectKey(oldObj, oldName, newName) {
    const newObj = {};

    console.log("in renameObjectKey");

    Object.keys(oldObj).forEach(key => {
        const value = oldObj[key];

        if (key === oldName) {
            newObj[newName] = value;
        } else {
            newObj[key] = value;
        }
    });

    return newObj;
}

class ParamsObject {
    constructor(value, tempId) {
        this.data = {message: value, tempId: tempId};
    }
}

exports.sendMessageNotification = functions.firestore.document('messages/{messageId}').onWrite((change, context) => {

        // Get an object representing the document
        // e.g. {'name': 'Marie', 'age': 66}
        const newValue = change.after.data();

        // ...or the previous value before this update
        const previousValue = change.before.data();

        console.log("newValue:", newValue);

        console.log("messageIdChange:", context.params.messageId);
        //console.log("prevValue:", previousValue);

        // access a particular field as you would any JS property
        //const name = newValue.name;

        var topic = 'all';

        let params = toPlainObject(new ParamsObject(newValue[context.params.messageId].message, newValue[context.params.messageId].timestamp));
        //params.data = toPlainObject(new WebObject());

        /*var payload = {
          data: {
            message: newValue.data.message
          }
        };*/

        admin.messaging().sendToTopic(topic, params).then((response) => {
          console.log("Successfully sent message:", response);
          //console.log("Message ID:", response.messageId);

          var newObj = renameObjectKey(newValue, newValue[context.params.messageId].timestamp, response.messageId);

          console.log("newObj:", newObj);

          firebaseHelper.firestore.updateDocument(db, 'messages', newValue[context.params.messageId].timestamp, newObj);
        }).catch((error) => {
          console.log("Error sending message:", error);
        });

        return null;
      });

Код, который не выполняется, находится внутри вызова функции messaging - я получаю сообщение, поэтому оно, по крайней мере, заходит так далеко, но онопохоже, не попадает в блок then:

admin.messaging().sendToTopic(topic, params).then((response) => {

          //*******DOESNT SEEM TO MAKE IT HERE*******

          console.log("Successfully sent message:", response);


          var newObj = renameObjectKey(newValue, newValue[context.params.messageId].timestamp, response.messageId);

          console.log("newObj:", newObj);

          firebaseHelper.firestore.updateDocument(db, 'messages', newValue[context.params.messageId].timestamp, newObj);
        }).catch((error) => {
          console.log("Error sending message:", error);
        });

Это все, что я вижу в журнале firebase functions:

2:43:14.793 PM
sendMessageNotification
Function execution took 682 ms, finished with status: 'ok'
2:43:14.508 PM
sendMessageNotification
messageIdChange: 1537382591952
2:43:14.497 PM
sendMessageNotification
newValue: { '1537382591952': { message: 'The relay seems to be malfunctioning.', name: 'eamon', timestamp: '1537382591952' } }
2:43:14.112 PM
sendMessageNotification
Function execution started

Я также должен увидеть вывод из:

console.log("Successfully sent message:", response);

как минимум ...

Что происходит?

1 Ответ

0 голосов
/ 19 сентября 2018

Вам необходимо вернуть обещание из вашей функции, которое разрешается, когда вся асинхронная работа завершена.Если вы этого не сделаете, Cloud Functions завершит вашу функцию, возможно, до того, как работа будет завершена.

В вашем случае вы должны поставить ключевое слово return перед admin.messaging()... вместо возврата null.

Пожалуйста, прочитайте документацию для получения дополнительной информации и посмотрите мои видео-серии о работе с обещаниями в облачных функциях .

...