【问题标题】:How do I call other Google APIs from a Cloud Function?如何从 Cloud Function 调用其他 Google API?
【发布时间】:2016-05-22 22:45:39
【问题描述】:

我想从我的云函数中调用其他 Google API,例如,在收到来自 Pubsub 的消息后将文件写入 Cloud Storage。我该怎么做?

【问题讨论】:

    标签: google-cloud-platform google-cloud-functions


    【解决方案1】:

    您可以使用google-cloud client library for Node.js 来完成此操作。同样的库也可用于 Java、Python 和 Ruby。

    例如在 Node JS 中,您需要相应地编辑您的 package.json 文件:

    {
      "dependencies": {
        "google-cloud": "*"
      },
      ...
    }
    

    然后,在您的代码中,您可以简单地调用相关库。以下示例仅列出项目中的存储桶:

    var gcloud = require('google-cloud');
    
    exports.helloworld = function(context, data) {
      var gcs = gcloud.storage({projectId: '<PROJECT>'});    
      gcs.getBuckets(function(err, buckets) {
        if (!err) {
          buckets.forEach(function(bucket) {
            console.log(bucket.name);
          });
        } else {
          console.log('error: ' + err);
        }
      });
    
      context.success();
    }
    

    您也不应该包含整个 google-cloud npm 模块,而是指定一个特定的子模块,例如上面例子中的require('@google-cloud/storage')

    【讨论】:

      猜你喜欢
      • 2018-01-24
      • 2018-08-13
      • 2020-12-17
      • 2017-12-17
      • 2020-06-19
      • 1970-01-01
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多