Почему Google Cloud Functions выдает ошибку «Недопустимое значение для config firebase.databaseURL» при попытке инициализировать приложение firebase? - PullRequest
0 голосов
/ 19 апреля 2019

У меня есть облачная функция Google, которая синхронизирует информацию о присутствии из базы данных Firebase в реальном времени с базой данных Firestore (как объяснено здесь ). Это соответствующий код облачных функций из связанного примера:

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

admin.initializeApp();

// Since this code will be running in the Cloud Functions enviornment
// we call initialize Firestore without any arguments because it
// detects authentication from the environment.
const firestore = admin.firestore();

// Create a new function which is triggered on changes to /status/{uid}
// Note: This is a Realtime Database trigger, *not* Cloud Firestore.
exports.onUserStatusChanged = functions.database.ref('/status/{uid}').onUpdate(
    (change, context) => {
      // Get the data written to Realtime Database
      const eventStatus = change.after.val();

      // Then use other event data to create a reference to the
      // corresponding Firestore document.
      const userStatusFirestoreRef = firestore.doc(`status/${context.params.uid}`);

      // It is likely that the Realtime Database change that triggered
      // this event has already been overwritten by a fast change in
      // online / offline status, so we'll re-read the current data
      // and compare the timestamps.
      return change.after.ref.once('value').then((statusSnapshot) => {
        const status = statusSnapshot.val();
        console.log(status, eventStatus);
        // If the current timestamp for this data is newer than
        // the data that triggered this event, we exit this function.
        if (status.last_changed > eventStatus.last_changed) {
          return null;
        }

        // Otherwise, we convert the last_changed field to a Date
        eventStatus.last_changed = new Date(eventStatus.last_changed);

        // ... and write it to Firestore.
        return userStatusFirestoreRef.set(eventStatus);
      });
    });

Недавно я получил электронное письмо от Google, в котором сообщалось, что мне нужно будет обновить NodeJS 6 до NodeJS 8 или 10. Поскольку эта конкретная функция еще не запущена, я продолжил работу и внес изменения в конфигурацию в Google Cloud. Приставка. Теперь я получаю ошибку ниже. Я попытался вернуться к NodeJS 6, воссоздать функцию с нуля, проверить проблемы с Github и другие онлайн-форумы. Похоже, что моя облачная функция Google больше не снабжена необходимыми переменными среды для соединения с Firebase / Firestore. Однако я не уверен, почему это так.

Error: Invalid value for config firebase.databaseURL: undefined
  at resourceGetter (/srv/node_modules/firebase-functions/lib/providers/database.js:101:19)
  at cloudFunctionNewSignature (/srv/node_modules/firebase-functions/lib/cloud-functions.js:102:13) 
  at /worker/worker.js:825:24 
  at <anonymous> at process._tickDomainCallback (internal/process/next_tick.js:229:7)

Эта ошибка также отображается в журналах Stackdriver для функции Cloud:

Warning, estimating Firebase Config based on GCLOUD_PROJECT. Initializing firebase-admin may fail

1 Ответ

1 голос
/ 20 апреля 2019

Вы должны повторно развернуть, используя Firebase CLI. Он делает некоторые особые действия в среде, чтобы помочь Firebase Admin SDK правильно инициализировать без каких-либо параметров (добавление FIREBASE_CONFIG). Похоже, что когда вы изменили среду выполнения в консоли, вы также потеряли эту специальную конфигурацию.

...