根据环境

时间:2018-04-23 14:03:31

标签: node.js typescript firebase google-cloud-functions

我是Node.js,Firebase Cloud Functions和TypeScript的新手。

我的目标是创建一个http端点的云功能,客户端可以使用Firebase进行身份验证。如果函数成功,我希望云函数返回自定义访问令牌。

我将两个Firebase项目用作不同的环境(developmentproduction)。我发现我需要使用ServiceAccountKey.json初始化Admin SDK。我的问题是我有两个不同的ServiceAccountKey文件,具体取决于运行该函数的环境。

我添加了一个配置变量,描述了哪些环境正在运行。我已经通过运行firebase functions:config:set app.environment="production"

来完成了这项工作

然后我的计划是通过检查此配置来获取正确的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)
    })
})

我正在寻找答案:

为什么此时无法读取配置变量?

根据环境变量初始化模块的最佳做法是什么?

修改 当我在本地提供函数时(如:firebase serve --only functions)。我收到错误:

  

我的功能:准备模拟功能。

     

⚠功能:无法加载功能源代码。通过在函数目录中运行npm i --save firebase-functions确保您拥有最新的SDK。

     

⚠功能:模拟器出错。解析函数触发器时出错。

     

TypeError:无法读取属性'环境'未定义的      在对象。 (/Users/mojnz/Git/mojnz/functions/lib/index.js:7:35)      在Module._compile(module.js:570:32)      在Object.Module._extensions..js(module.js:579:10)      在Module.load(module.js:487:32)      在tryModuleLoad(module.js:446:12)      在Function.Module._load(module.js:438:3)      在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      在对象。 (/usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:61:3)

我确实使用npm i --save firebase-functions更新了SDK。

1 个答案:

答案 0 :(得分:2)

如果您想在本地测试时使用环境变量(使用servefunctions:shell),则必须采取额外步骤才能显示它们。它是documented on this page

  

如果您正在使用自定义函数配置变量,请先运行   获取自定义配置的命令(在函数中运行)   目录),然后运行shell:

firebase functions:config:get > .runtimeconfig.json firebase
functions:shell

每次要更改版本时,您都必须在.runtimeconfig.json文件夹中重新创建functions文件。