首页 文章

如何在PC上本地测试Firebase的 Cloud 功能

提问于
浏览
24

今天Firebase发布了它的全新产品Cloud Functions for Firebase,我刚创建了一个hello world功能并将其部署在我现有的firebase项目上 .

看起来它捆绑了所有依赖项并将其上传到firebase,就像 aws lambda function 一样 . 但即使在代码的微小变化上也需要太多时间才能完成,并且还需要良好的互联网连接 . 如果由于某种原因您处于脱机状态,那么在您可以在本地计算机上执行和测试该功能的方法之前,您所处的代码就处于黑暗状态 .

Is there any way to test Cloud Functions for Firebase locally?

7 回答

  • 1

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

    Google Cloud Functions还开源了本地模拟器,我们正在努力与Cloud Functions for Firebase Build 更紧密的集成 . 同时,你可以在这里查看:https://github.com/GoogleCloudPlatform/cloud-functions-emulator/模拟器允许你在本地运行功能 . 以下是解释如何使用它的文档:https://cloud.google.com/functions/docs/emulator

  • 0

    这里有一个firebaser

    部署您的函数确实比我通常愿意等待的时间更长 . 我们正在努力改进这一点,并且(正如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;
    

    然后在我的函数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 });
      });
    });
    

    因此,您可以看到最后一个文件实际上只是将"worker method" ocr.extract_text 连接到数据库位置 .

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

  • 22

    这里有一个firebaser

    还没 . 有一个 Cloud 功能emulator但它目前不支持使用Firebase SDK编写的功能 . 本地模拟器支持位于我们的列表顶部,我们很快就会有所收获 .

  • 9

    本地运行功能

    https://firebase.google.com/docs/functions/local-emulator

    要使用此功能,firebase-tools必须具有最低版本3.8.0,而firebase-functions SDK必须具有最低版本0.5.7 . 要更新它们,请在项目的functions /目录中运行以下命令:npm install --save firebase-functions
    npm install -g firebase-tools
    要在本地运行函数,请使用firebase serve:firebase serve --only函数#仅模拟函数
    警告:实验性功能 . 这是一项实验性功能,目前仅支持HTTPS功能的模拟 .

    UPDATE:

    Hey Functions Trusted Testers,我们刚刚发布了firebase-tools v3.11.0,它支持一个交互式shell,用于模拟所有类型的函数,并使用测试数据调用它们 . 感谢您的许多人参与此功能的反馈 Session . 请参阅我们的文档,了解如何使用这个令人兴奋的新功能! https://firebase.google.com/docs/functions/local-emulator#use_the_cloud_functions_shell

  • 0

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

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

    如果已安装,则可以将其更新为最新版本 . 通常,函数模拟器具有上述依赖性,但我仍然建议您更新它,

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

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

    firebase serve --only functions
    

    我希望它有所帮助!

  • 16

    起初我无法完成单步操作 . 我的流程与此处的许多答案中记录的相同 .

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

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

    # start the emulator
    functions start
    
    # allow inspection
    functions inspect helloWorld
    
    # call the function from the cli
    functions call helloWorld
    

    这很有效,我可以打破一个断点 .

    但是,当在邮递员或浏览器中访问该功能的 endpoints 时,我根本没有得到任何响应 .

    我缺少的步骤是:

    # deploy the function to the emulator
    functions deploy helloWorld --trigger-http
    
    # you need to toggle inspection after the deploy
    functions inspect helloWorld
    

    现在我可以从postman或浏览器中点击该函数的 endpoints ,并且命中断点 .

    我推荐精彩的NiM chrome extension进行调试并希望这个答案可以帮助某人,即使这是一个老问题 .

  • -1

    现在有一个 Cloud functions emulator that允许您在本地调用函数

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

相关问题