我正在尝试部署一个函数,该函数根据我在部署之前设置的环境变量使用 firebase 配置变量。这在登台上效果很好(一个单独的项目,看起来几乎与生产相同,除了几个环境变量),但在生产上失败并出现错误 TypeError: Cannot read property 'env' of undefined
指向functions.config().app.env
(参见下面的代码)。
如果我在线浏览https://console.cloud.google.com/functions/details/us-central1/<functionName>?project=<projectName>
中的功能.runtimeconfig.json
文件似乎没有获取我在部署到生产环境之前设置的环境变量,而它在暂存时完美地做到了这一点。
如果我设置app.env
到“暂存”,它非常适合我的暂存环境,并且不会显示任何错误。我试过cd
-进入函数文件夹以设置环境变量,然后在部署之前退出,但它没有改变任何事情。我什至尝试将其写入 .runtimeconfig.json
在函数文件夹中(尽管这只需要本地测试),但这也没有效果。
编辑:经过更多测试后发现 .runtimeconfig
在线浏览时可以看到,函数代码是根据我通过 CLI 在本地设置的函数配置生成的,并在部署时上传。每当我更新它时,它似乎都会很好地复制到登台上,但不会在生产中执行相同的操作。我就是不明白为什么...
我的功能:
const functions = require('firebase-functions')
// Stripe needs to be set with its key when the library is being required
const stripe = require("stripe")(functions.config().app.env === 'staging' ? functions.config().stripe.key.staging : functions.config().stripe.key.production)
// ^^^ this is what the error is pointing to
module.exports = functions.https.onCall(async (data, context) => {
// ... doin' some stripe magic
})
我在 shell 命令行环境中使用 npm:
firebase functions:config:set app.env="production" && firebase deploy -P production --only functions
firebase use
的输出:
% firebase use
Active Project: default (<stagingProjectName>)
Project aliases for <projectFolderPath>:
* default (<stagingProjectName>)
production (<productionProjectName>)
Run firebase use --add to define a new project alias.
firebase functions:config:get
的输出(以及其他变量):
{
"app": {
"env": "production"
}
}
最佳答案
我通过首先切换到生产项目、设置变量,然后从那里进行部署来解决这个问题。
firebase use production
firebase functions:config:set someservice.key="keyvalue" ...
firebase deploy --only functions
尽管我之前在部署命令中使用了 -P
标志(firebase -P production
- 请参阅问题),但没有设置适当的配置值,显然。
关于javascript - Firebase 功能配置不会部署,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65761138/