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

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

问题描述

今天,Firebase发布了全新的 Firebase云端函数,我刚刚创建了一个hello然后将其部署到我现有的firebase项目中。

它看起来像捆绑了所有依赖关系,并将其上传到firebase,就像 aws lambda function 确实。但即使对代码进行细微的更改,也需要花费太多的时间来完成,并且还需要良好的互联网连接。如果你因为某种原因而离线,那么你只是在黑暗中编写代码,直到你有办法在本地机器上离线执行和测试这些函数。

是否有任何方法可以在本地测试Firebase的云端函数?

解决方案

/ em>



部署你的函数的确需要比我通常愿意等待的更多的时间。我们正在努力改善这一点(正如布伦丹所说)正在开发一个本地模拟器。



但是目前,我主要将我的实际业务逻辑写入首先单独的Node脚本。这样我可以从本地命令提示符下使用节点speech.js 来测试它。一旦我满意的功能,我要么复制/粘贴到我的实际函数文件或(更好)导入语音模块到我的函数文件,并调用它从在那里。



我很快挖掘出的一个缩写例子就是当我使用Cloud Vision API进行文本提取。我有一个名为 ocr.js 的文件,其中包含:

  var fetch = require('node-fetch'); 
$ b函数extract_text(url,gcloud_authorization){
console.log('extract_text from image'+ url +'with authorization'+ gcloud_authorization); (函数(res){
return res.buffer();
})。then(function(buffer){
(https://vision.googleapis.com/v1/images:annotate?key='+gcloud_authorization,{
method:POST,
headers:{
Content类型:application / json
},
body:JSON.stringify({
requests:[
{
image:{
content:buffer.toString('base64')
},
features:[
{
type:TEXT_DETECTION,
maxResults:1
}
]
}
]
})
});
})。 res){
var json = res.json(); $ b $ if(res.status> = 200&& res.status< 300){
return json;
} else {
return json.then(Promise.reject.bind(Promise));
}
} )。然后(函数(json){
if(json.responses&& json.responses.length&& json.responses [0] .error){
return Promise.reject(json.responses [0] .error);
}
返回json.responses [0] .textAnnotations [0] .description;
});
}

if(process.argv.length> 2){
//通过传递图片URL和gcloud访问令牌,可以测试这个模块
process.argv.forEach(a => console.log(a));
extract_text(
process.argv [2],//图像URL
process.argv [3] // gcloud访问标记或API键
).then(function ){
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');
$ b $ exports.ocr = functions.database().path('/ messages / {room} / {id}')。onWrite(function(event){
console.log(' OCR触发/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; //只有OCR图像

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

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

所以你可以看到这个最后一个文件实际上只是为了配置worker method ocr.extract_text 到数据库位置。

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


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.

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.

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

解决方案

firebaser here

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.

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.

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;

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 });
  });
});

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

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上本地测试Firebase的云端功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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