我是 Node.js、Firebase Cloud Functions 和 TypeScript 的新手。
我的目标是创建一个作为 http 端点的云函数,客户端可以通过 Firebase 进行身份验证。如果函数成功,我希望云函数返回自定义访问 token 。
我使用两个 Firebase 项目作为不同的环境(开发
和生产
)。我发现我需要使用 ServiceAccountKey.json
初始化 Admin SDK。我的问题是,我有两个不同的 ServiceAccountKey 文件,具体取决于函数运行的环境。
我添加了一个配置变量来描述正在运行的环境。我通过运行以下命令来完成此操作: firebasefunctions:config:set app.environment="product"
然后我的计划是通过检查此配置来派生正确的 ServiceAccountKey 的路径。
这是我的整个index.ts 文件。
import * as functions from 'firebase-functions';
const admin = require('firebase-admin');
const serviceAccountKeyPath = functions.config().app.environment === 'development' ? '../mojnz-development-key.json' : '../mojnz-production-key.json';
const serviceAccount = require(serviceAccountKeyPath);
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://mojnz-dev.firebaseio.com"
});
export const testFunc = functions.https.onRequest((request, response) => {
const berp = "123"
admin.auth().createCustomToken(berp).then((value) => {
console.log("Did create custom token:", value)
response.sendStatus(200)
}).catch((error) => {
console.log("Error creating custom token:", error)
response.sendStatus(500)
})
})
我正在寻找以下问题的答案:
为什么此时无法读取配置变量?
如何根据环境变量初始化模块的最佳实践?
编辑
当我在本地提供函数时(如下所示:firebaseserve--onlyfunctions
)。我收到错误:
i functions: Preparing to emulate functions.
⚠ functions: Failed to load functions source code. Ensure that you have the latest SDK by running npm i --save firebase-functions inside the functions directory.
⚠ functions: Error from emulator. Error occurred while parsing your function triggers.
TypeError: Cannot read property 'environment' of undefined at Object. (/Users/mojnz/Git/mojnz/functions/lib/index.js:7:35) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.require (module.js:497:17) at require (internal/module.js:20:19) at /usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:21:11 at Object. (/usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:61:3)
我确实使用 npm i --save firebase-functions
更新了 SDK。
最佳答案
如果您想在本地测试时使用环境变量(使用 serve
或 functions:shell
),目前您必须采取额外的步骤才能使它们显示向上。这是documented on this page :
If you're using custom functions configuration variables, first run the command to get your custom config (run this within the functions directory), and then run the shell:
firebase functions:config:get > .runtimeconfig.json firebase functions:shell
每次您想要更改变量时,都必须在 functions
文件夹中重新创建 .runtimeconfig.json
文件。
关于node.js - 根据环境使用凭据初始化 Admin SDK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49983147/