Firebase Functions 1.0.0 migration: Trouble with custom initializeApp() with Google Service Account credential

纵然是瞬间 提交于 2019-12-13 00:36:20

问题


I just updated from the beta (v0.9.1) to v1.0.0, and ran into some problems with initialization. As per the migration guide, functions.config().firebase is now deprecated. Here is my initialization before:

const serviceAccount = require('../service-account.json')

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: functions.config().firebase.databaseURL,
  storageBucket: functions.config().firebase.storageBucket,
  projectId: functions.config().firebase.projectId,
})

Here is what I changed it to after upgrading:

admin.initializeApp()

At first this seems to work fine, the databaseURL and storageBucket are being recognized. However, there is a problem regarding the newly absent credential field. That field is required in order to access Google Cloud Storage. I access the @google-cloud/storage API in my app like so:

import { Bucket, File } from '@google-cloud/storage'
import * as admin from 'firebase-admin'

bucket: Bucket = admin.storage().bucket()

    this.bucket
      .upload(filepath, {
        destination: uploadPath,
      })
      .then((fileTuple: [File]) => {
        // after uploading, save a reference to the audio file in the DB
        fileTuple[0]
          .getSignedUrl({ action: 'read', expires: '03-17-2025' })
          .then((url: [string]) => {
            dbRef.child('audioFiles').push(url[0])
          })
          .catch(err => console.log('Error:', err))

        console.log(`${filepath} uploaded to ${this.bucket.name}.`)
      })

This uploads a file to storage, then it inserts the signed URL into my Realtime Database.

After migration, this chunk of code gives the following error:

SigningError: Cannot sign data without `client_email`

Since client_email was a field on service-account.json, I suspect that I need to reinsert credentials, like so:

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
})

When I try this, however, I get errors like Error: Can't determine Firebase Database URL. or Error: Bucket name not specified or invalid.. So if I manually insert credential, it appears to expect databaseURL and storageBucket to be manually inserted as well.

So the question is, how do I do this?


回答1:


Figured it out myself. I had to rewrite my init call like this:

const serviceAccount = require('../service-account.json')
const firebaseConfig = JSON.parse(process.env.FIREBASE_CONFIG)

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: firebaseConfig.databaseURL,
  storageBucket: firebaseConfig.storageBucket,
  projectId: firebaseConfig.projectId,
})


来源:https://stackoverflow.com/questions/49697107/firebase-functions-1-0-0-migration-trouble-with-custom-initializeapp-with-goo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!