40

今天 Firebase 发布了它的全新产品Cloud Functions for Firebase,我刚刚创建了一个 hello world 函数并将其部署到我现有的 firebase 项目中。

看起来它捆绑了所有依赖项并将其上传到 firebase,就像aws lambda 函数一样。但是即使代码的微小变化也需要花费太多时间,并且还需要良好的互联网连接。如果您由于某种原因处于离线状态,那么在您有办法在本地计算机上离线执行和测试该功能之前,您将一无所知您正在编写什么代码。

有什么方法可以在本地测试 Cloud Functions for Firebase?

4

9 回答 9

23

火力基地在这里

部署您的功能确实需要比我通常愿意等待的时间更多的时间。我们正在努力改进这一点,并且(正如 Brendan 所说)正在开发本地模拟器。

但目前,我主要是先将我的实际业务逻辑写入一个单独的 Node 脚本。这样我就可以在本地命令提示符下使用node speech.js. 一旦我对函数的工作感到满意,我要么将它复制/粘贴到我的实际函数文件中,要么(更好地)将speech模块导入我的函数文件并从那里调用它。

我很快找到的一个简短示例是当我使用 Cloud Vision API 连接文本提取时。我有一个名为的文件ocr.js,其中包含:

var fetch = require('node-fetch');

function extract_text(url, gcloud_authorization) {
  console.log('extract_text from image '+url+' with authorization '+gcloud_authorization);

  return fetch(url).then(function(res) {
    return res.buffer();
  }).then(function(buffer) {
    return fetch('https://vision.googleapis.com/v1/images:annotate?key='+gcloud_authorization, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        "requests":[
          {
            "image":{
              "content": buffer.toString('base64')
            },
            "features":[
              {
                "type":"TEXT_DETECTION",
                "maxResults":1
              }
            ]
          }
        ]
      })
    });
  }).then(function(res) {
    var json = res.json();
    if (res.status >= 200 && res.status < 300) {
      return json;
    } else {
      return json.then(Promise.reject.bind(Promise));
    }
  }).then(function(json) {
    if (json.responses && json.responses.length && json.responses[0].error) {
      return Promise.reject(json.responses[0].error);
    }
    return json.responses[0].textAnnotations[0].description;
  });
}

if (process.argv.length > 2) {
  // by passing the image URL and gcloud access token, you can test this module
  process.argv.forEach(a => console.log(a));
  extract_text(
    process.argv[2], // image URL
    process.argv[3]  // gcloud access token or API key
  ).then(function(description) {
    console.log(description);
  }).catch(function(error) {
    console.error(error);
  });
}

exports.extract_text = extract_text;

然后在我的 Functions index.js 中,我有:

var functions = require('firebase-functions');
var fetch = require('node-fetch');
var ocr = require('./ocr.js');

exports.ocr = functions.database().path('/messages/{room}/{id}').onWrite(function(event) {
  console.log('OCR triggered for /messages/'+event.params.room+'/'+event.params.id);

  if (!event.data || !event.data.exists()) return;
  if (event.data.ocr) return;
  if (event.data.val().text.indexOf("https://firebasestorage.googleapis.com/") !== 0) return; // only OCR images

  console.log(JSON.stringify(functions.env));

  return ocr.extract_text(event.data.val().text, functions.env.googlecloud.apikey).then(function(text) {
    return event.data.adminRef.update({ ocr: text });
  });
});

如您所见,最后一个文件实际上只是将“工作方法”ocr.extract_text连接到数据库位置。

请注意,这是不久前的一个项目,因此某些语法(主要是functions.env部分)可能有所改变。

于 2017-03-11T00:41:06.870 回答
21

火力基地在这里

要在本地调试 Cloud Functions for Firebase,有一个模拟器。有关更多信息,请参阅文档

于 2017-03-10T20:30:50.637 回答
10

在本地运行和调试/检查函数

先决条件(谷歌云功能和特定于firebase):

npm install -g @google-cloud/functions-emulator
npm install --save firebase-functions
npm install -g firebase-tools

运行和检查/调试:首先在本地运行函数,然后检查每个函数,最后运行每个特定函数进行调试+检查。functions start用作替代firebase serve工具并注意每个工具的文档可用(且有用)。

按预期运行和调试特定功能myFn(例如,在 Nodejs 中通过chrome://inspect并注意这使用 Nodejs v10 虽然不受官方支持):

firebase serve --only functions
functions inspect myFn
functions call myFn # or call from browser

附加文件:

https://firebase.google.com/docs/functions/local-emulator https://cloud.google.com/functions/docs/emulator#debug-emulator https://github.com/GoogleCloudPlatform/cloud-functions-模拟器/维基

于 2017-07-12T16:23:52.470 回答
3

>> 有什么方法可以在本地测试 Cloud Functions for Firebase?

您可以使用以下命令启动 firebase shell(在您的函数目录中执行):

npm run build && firebase functions:shell

你可以像这样在 shell 中调用你的函数:

helloWorld()

有关更多信息,请参阅链接。

于 2020-02-18T07:59:46.147 回答
1

在这里回答:https ://github.com/firebase/firebase-functions/issues/4#issuecomment-286515989

Google Cloud Functions 还开源了一个本地模拟器,我们正在努力与 Cloud Functions for Firebase 建立更紧密的集成。同时,您可以在此处查看: https ://github.com/GoogleCloudPlatform/cloud-functions-emulator/

模拟器确实允许您在本地运行功能。这是解释如何使用它的文档: https ://cloud.google.com/functions/docs/emulator

于 2017-03-16T13:02:58.000 回答
1

起初我无法让单步工作。我的过程与此处许多答案中记录的过程相同。

此外,这些页面几乎包含我需要的所有文档:

我已经使用 运行了函数firebase serve --only functions,但没有启动并运行调试器。然后我遇到了直接使用模拟器的另一种方式,并设法达到了这样的断点:

# start the emulator
functions start

# allow inspection
functions inspect helloWorld

# call the function from the cli
functions call helloWorld

这行得通,我可以打断点。

但是,当在邮递员或浏览器中点击函数的端点时,我根本没有得到任何响应。

我缺少的步骤是:

# deploy the function to the emulator
functions deploy helloWorld --trigger-http

# you need to toggle inspection after the deploy
functions inspect helloWorld

现在我可以从邮递员或浏览器中命中函数的端点,并且断点被命中。

我推荐使用出色的NiM chrome 扩展进行调试,并希望这个答案对某人有所帮助,即使这是一个老问题。

于 2018-10-31T16:39:31.873 回答
0

对于调试 HTTP 函数(webhooks 等)的 vscode 用户...

谷歌云模拟器 ( firebase serve --only functions) 会启动一个单独的进程来运行您的函数。您可以使用 vscode 附加到此进程,但由于模拟器仅在调用第一个函数后创建此进程,因此并不简单。

  • 在您的函数中创建一个虚拟 HTTP 端点,该端点将返回 processID:
app.get("/processid", function(request, response) {
  response.send(`${process.pid}`);
});
  • 启动模拟器firebase serve --only functions
  • 调用http://<localhost_url>/processid端点。这将创建进程并返回 processID
  • 使用 vscode 附加到指定的进程。您现在可以在任何其他函数上设置断点、步骤等(它们都使用相同的过程)。

可能有更好的方法将所有这些粘合在一起。

于 2019-02-01T19:07:56.767 回答
0

首先,我建议您安装以下依赖项,

npm install --save firebase-functions
npm install -g firebase-tools 

如果已经安装,那么您可以将其更新到最新版本。通常,functions-emulator 具有上述依赖项,但我仍然建议您更新它,

npm install -g @google-cloud/functions-emulator

更新后,转到应用程序的功能文件夹并运行以下命令,

firebase serve --only functions

我希望它有帮助!

于 2018-02-24T12:54:51.713 回答
-2

现在有一个云函数模拟器,可让您在本地调用函数

完成 PoC 后,我将更新此答案以包含我使用的代码和步骤。

于 2017-07-25T15:29:16.543 回答