【问题标题】:How to reuse code in firebase cloud functions如何在 Firebase 云函数中重用代码
【发布时间】:2020-01-15 06:15:06
【问题描述】:

我将我的 firebase 云函数设置为单个文件 (functionName.f.js),然后我的 index.js 文件使用以下代码将文件导出为函数:

index.js 文件

for (let f = 0, fl = files.length; f < fl; f++) {
  const file = files[f];
  const functionName = camelCase(file.slice(0, -5).split('/').join('_')); // Strip off '.f.js'
  if (!process.env.FUNCTION_NAME || process.env.FUNCTION_NAME === functionName) {
    exports[functionName] = require(file);
  }

}

exports = module.exports.function1 = function1();
exports = module.exports.function2 = function2();

//omitted function1 and function2 code

我正在尝试在多个不同的函数文件中重用代码。目前我有我想在我的'index.js'文件中重用的函数 - 然后我在我想要调用这些函数的任何函数文件中引用 index.js 文件,如下所示:

function1.f.js 文件

const helpers = require('../index');
const functions = require('firebase-functions');
const admin = require('firebase-admin');

exports = module.exports = functions.https.onCall(async (data, context) => {
await helpers.function1;
}

问题是,当 function1 像上面那样被引用时 - function2 似乎也执行了,即使它从未被调用过。

我的 eslintrc.json 文件的相关部分

  "parserOptions": {
    // Required for certain syntax usages
    "ecmaVersion": 2018,
    "sourceType": "module"
  },

【问题讨论】:

  • 怎么看出调用了函数2?
  • 我为每个执行的函数设置了日志。

标签: javascript firebase google-cloud-functions


【解决方案1】:

我认为您在使用 exports 变量时做错了。我已经复制了它,它的工作方式如下:

module.exports = {
        function1,
        function2 
}

然后用 () 调用它,例如:helpers.function1()

这应该可以正常工作。

【讨论】:

    猜你喜欢
    • 2019-06-24
    • 2021-09-05
    • 2020-08-03
    • 1970-01-01
    • 2018-12-16
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    相关资源
    最近更新 更多