Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google-cloud TypeError: gcs.bucket is not a function

I am trying to implement cloud function but getting error if i require it like this

   var storage =require('@google-cloud/storage')(); 

like this when deploying

var storage = require('@google-cloud/storage');

so i resolved to using it as above but tried uploading a picture i am getting error "TypeError: gcs.bucket is not a function"

const os = require('os');
const path = require('path');

///

exports.onFileChange = functions.storage.object().onFinalize((event) => {
 const bucket = event.bucket;
 const contentType = event.contentType;
 const filePath = event.name;
 console.log('Changes made to bucket');

///

 if(path.basename(filePath).startsWith('renamed-')){
     console.log("File was previously renamed");
     return;
 }
 const gcs = storage({
    projectId: 'clfapi'
  });

///

 const destBucket = gcs.bucket(bucket);
 const tmFiilePath = path.join(os.tmpdir(), path.basename(filePath));
 const metadata = {contentType: contentType};

///

 return destBucket.file(filePath).download({
     destination: tmFiilePath
 }).then(() => {
     return destBucket.upload(tmFiilePath, {
         destination: 'renamed-' + path.basename(filePath),
         metadata: metadata
     })
   });
});
like image 623
R.Ovie Avatar asked Oct 28 '18 15:10

R.Ovie


1 Answers

The API changed in version 2.x of the Cloud Storage node SDK. According to the documentation, you import the SDK like this:

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

Then you can create a new Storage object:

// Creates a client
const storage = new Storage();

Then you can reach into a bucket:

const bucket = storage.bucket()
like image 77
Doug Stevenson Avatar answered Sep 27 '22 22:09

Doug Stevenson