I would like to call other Google APIs from my cloud function, for example, to write a file to Cloud Storage after receiving a message from Pubsub. How can I do this?
You specify triggers as part of function deployment. You cannot bind the same function to more than one trigger at a time, but you can have the same event cause multiple functions to execute by deploying multiple functions with the same trigger settings.
You can use the google-cloud client library for Node.js to accomplish this. The same library is also available for Java, Python and Ruby.
For example in Node JS, you'll want to edit your package.json file accordingly:
{
"dependencies": {
"google-cloud": "*"
},
...
}
Then, in your code, you can simply invoke the relevant library. The following example just lists the buckets in the project:
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();
}
You also shouldn't include the entire google-cloud
npm module, but instead specify a specific sub-module, e.g. require('@google-cloud/storage')
in the above example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With