Как исправить ошибку облачной функции admin.database.ref не является функцией при экспорте - PullRequest
0 голосов
/ 26 марта 2019

В настоящее время я пытаюсь изменить свои облачные функции и перейти под https.onRequest, чтобы я мог позвонить и использовать его для планирования работы cron. Как это я получаю следующую ошибку в журналах.

TypeError: admin.database.ref не является функцией at exports.scheduleSendNotificationMessageJob.functions.https.onRequest (/user_code/index.js:30:20) в cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:57:9)

exports.scheduleSendNotificationMessageJob = functions.https.onRequest((req, res) => {
    admin.database.ref('/notifications/{studentId}/notifications/{notificationCode}')
        .onCreate((dataSnapshot, context) => {
            const dbPath = '/notifications/' + context.params.pHumanId + '/fcmCode';
            const promise = admin.database().ref(dbPath).once('value').then(function(tokenSnapshot) {
                const theToken = tokenSnapshot.val();
                res.status(200).send(theToken);
                const notificationCode = context.params.pNotificationCode;
                const messageData = {notificationCode: notificationCode};
                const theMessage = {    data: messageData,
                    notification: { title: 'You have a new job reminder' }
                };
                const options = {   contentAvailable: true,
                    collapseKey: notificationCode };
                const notificationPath = '/notifications/' + context.params.pHumanId + '/notifications/' + notificationCode;
                admin.database().ref(notificationPath).remove();
                return admin.messaging().sendToDevice(theToken, theMessage, options);
            });
            return null;
        });
});

1 Ответ

3 голосов
/ 26 марта 2019

Нельзя использовать определение onCreate() Триггера базы данных реального времени в пределах определения функции облака HTTP.

Если вы переключаетесь на облачную функцию HTTP «, чтобы (вы) могли звонить, используйте ее для планирования задания cron», это означает, что триггером будет вызов облачной функции HTTP . Другими словами, вы больше не сможете запускать действие (или функцию облака) при создании новых данных в базе данных реального времени.

Что вы можете очень хорошо сделать, это прочитать данные базы данных реального времени, например, следующим образом (упрощенный сценарий отправки уведомления):

exports.scheduleSendNotificationMessageJob = functions.https.onRequest((req, res) => {

    //get the desired values from the request
    const studentId = req.body.studentId;
    const notificationCode = req.body.notificationCode;

    //Read data with the once() method
    admin.database.ref('/notifications/' + studentId + '/notifications/' + notificationCode)
     .once('value')
     .then(snapshot => {
         //Here just an example on how you would get the desired values
         //for your notification
         const theToken = snapshot.val();
         const theMessage = ....
         //......

         // return the promise returned by the sendToDevice() asynchronous task
         return admin.messaging().sendToDevice(theToken, theMessage, options)
      })
      .then(() => {
         //And then send back the result (see video referred to below)
         res.send("{ result : 'message sent'}") ;
      })
      .catch(err => {
         //........
      });

});

Вы можете посмотреть следующее официальное видео Firebase о функциях HTTP Cloud: https://www.youtube.com/watch?v=7IkUgCLr5oA&t=1s&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM&index=3. В нем показано, как читать данные из Firestore, но концепция чтения и отправки ответа (или ошибки) одинакова для База данных в реальном времени. Вместе с двумя другими видеороликами из серии (https://firebase.google.com/docs/functions/video-series/?authuser=0),) также объясняется, как важно правильно связать обещания и указать платформе, что работа облачной функции завершена.

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