Robson Oliveira Alves
Robson Oliveira Alves

Reputation: 11

REACT - Resize image on Google-Cloud-Storage - Error to use bucket

I was following the Academind's youtube video to "Firebase Cloud Functions - Resizing Images after Upload" but I'm stuck trying to solve a problem with storage.bucket(bucket).

This are the error that I'm facing:

1. (node:2) MetadataLookupWarning: received unexpected error = URL is not defined code = UNKNOWN
2. Error: Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.
    at new ApiError (/srv/node_modules/@google-cloud/common/build/src/util.js:59:15)
    at Util.parseHttpRespMessage (/srv/node_modules/@google-cloud/common/build/src/util.js:161:41)
    at Util.handleResp (/srv/node_modules/@google-cloud/common/build/src/util.js:135:76)
    at Duplexify.requestStream.on.on.res (/srv/node_modules/@google-cloud/storage/build/src/file.js:823:31)
    at emitOne (events.js:116:13)
    at Duplexify.emit (events.js:211:7)
    at emitOne (events.js:116:13)
    at DestroyableTransform.emit (events.js:211:7)
    at onResponse (/srv/node_modules/retry-request/index.js:200:19)
    at PassThrough.<anonymous> (/srv/node_modules/retry-request/index.js:152:11) 

Code:

exports.onFileChange = functions.storage.object().onFinalize((object, context) => {
  // ...
  // Extract object data - left out to focus on the other parts of the function
  const {Storage} = require('@google-cloud/storage');

  // Creates a client
  const storage = new Storage({
      projectId: "dude-garden-care"
  });
  console.log(object, context)
  const bucket = object.bucket;
  const contentType = object.contentType;
  const filePath = object.name;

  if (object.resourceState === 'not_exists') {
    console.log('We deleted a file, exit...')
    return
  }


  if (path.basename(filePath).startsWith('resized-')) {
    console.log('We already renamed that file!')
    return
  }


  const destBucket = storage.bucket(bucket)
  const tmpFilePath = path.join(os.tmpdir(), path.basename(filePath))
  const metadata = { contentType: contentType }
  return destBucket
    .file(filePath)
    .download({
      destination: tmpFilePath,
    })
    .then(() => {
      return spawn('convert', [tmpFilePath, '-resize', '500x500', tmpFilePath])
    })
    .then(() => {
      return destBucket.upload(tmpFilePath, {
        destination: 'resized-' + path.basename(filePath),
        metadata: metadata,
      })
    })
})

Thanks a lot for y'all help

Upvotes: 0

Views: 140

Answers (1)

Robson Oliveira Alves
Robson Oliveira Alves

Reputation: 11

I solved the problem using

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

Hope it can help someone.

Upvotes: 1

Related Questions