如何在 PC 上本地测试 Cloud Functions for Firebase [英] how to test Cloud Functions for Firebase locally on pc

查看:19
本文介绍了如何在 PC 上本地测试 Cloud Functions for Firebase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Today Firebase released its brand new product Cloud Functions for Firebase and I just created a hello world function and deploy it on my existing firebase project.

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

It looks like it bundles all dependencies and upload it to firebase just like aws lambda function does. But it takes too much time to be done even on minor changes in code and also need a good connectivity of internet . If you are offline for some reason, you are just in dark what code you are writing until you have a way to execute and test that functions offline on your local machine.

有没有办法在本地测试 Cloud Functions for Firebase?

推荐答案

firebaser here

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

Deployment of your Functions indeed takes more time than what I'm normally willing to wait for. We're working hard to improve that and (as Brendan said) are working on a local emulator.

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

But for the moment, I mostly write my actual business logic into a separate Node script first. That way I can test it from a local command prompt with node speech.js. Once I'm satisfied that the function works, I either copy/paste it into my actual Functions file or (better) import the speech module into my functions file and invoke it from there.

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

One abbreviated example that I quickly dug up is when I was wiring up text extraction using the Cloud Vision API. I have a file called ocr.js that contains:

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 中,我有:

And then in my Functions index.js, I have:

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 连接到数据库位置.

So as you can see this last file is really just about wiring up the "worker method" ocr.extract_text to the database location.

注意这是一个前一段时间的项目,所以一些语法(主要是 functions.env 部分)可能已经改变了一点.

Note this is a project from a while ago, so some of the syntax (mostly the functions.env part) might have changed a bit.

这篇关于如何在 PC 上本地测试 Cloud Functions for Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆