5
votes

First question here.

I am trying to write a firebase cloud function to compress a file. I went through a lot of examples on the web but my code keeps getting stuck at two points.

1.const {gcs} =require('@google-cloud/storage')();

When I use this construct in require , I get the following error

TypeError: require(...) is not a function

If I change this to const {gcs} =require('@google-cloud/storage'); the error goes away but apparently the object isn't initialized because I get this error when I try to access it like so

TypeError: Cannot read property 'bucket' of undefined at exports.onfilechangecompressor.functions.storage.object.onFinalize.object (/user_code/index.js:21:27) at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23) at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20) at /var/tmp/worker/worker.js:733:24 at process._tickDomainCallback (internal/process/next_tick.js:135:7)

This is the line where I use gcs like so

const destBucket = gcs.bucket(bucket); where bucket is the object.bucket returned ( object is returned by onFinalize ).

Can someone please tell me how to initialize the storage so it works and returns a valid object.

My node.js version is 8.12.0 firebase version is 5.1.1

1
Is your bucket name correct?Alchemist Shahed
What version of @google-cloud/storage are you using? The APIs changed in 2.0.0.Doug Stevenson
@AlchemistShahed - I am using the default bucket so there is no bucket name.Aashwina Mouli
@DougStevenson- The version of @google-cloud/storage is 2.1.0.Aashwina Mouli

1 Answers

9
votes

The documentation for 2.x shows this:

const {Storage} = require('@google-cloud/storage');

You're adding () after the require, which you're discovered is not correct.

You then go on to initialize it like this:

// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';

// Creates a client
const storage = new Storage({
  projectId: projectId,
});

You may not need to specify the project id if you're running in Cloud Functions or other Google environments.

After that, you can get a reference to your default bucket:

storage.bucket()

You can also use the Admin SDK to invoke the same cloud storage APIs:

const admin = require('firebase-admin');
admin.initializeApp();
const storage = admin.storage();
storage.bucket();