4
votes

I have created a Cloud Function that trigger on any new file upload in Firebase Storage. Once successful upload function will update its metadata, but even though setting new metadata with 'setMetadata()' is not getting applied. There is no error during the process and but on checking for updated metadata, the new one is not reflecting.

exports.onImageUpload = functions.storage.object().onFinalize(async (object) => {  
  const storageRef = admin.storage().bucket(object.bucket);

  var metadata = {
      'uploader': 'unknown'   
  }

  await storageRef.file(object.name).setMetadata(metadata).then(function(data) {
    console.log('Success');
    console.log(data);
    return;
  }).catch(function(error) {
    console.log(error);
    return ;
  });
  return;
}); 

There is no error, and on Cloud Function log its printing 'Success' message. Also "metageneration: '2'" property also got updated, which means it should have updated metadata with new values, but it didn't.

1

1 Answers

9
votes

The problem comes from the fact that if you want to set custom key/value pairs they must be in the metadata key of the object you pass to the setMetadata() method, i.e. the metadata object in your case. This is explained in the API Reference Documentation for node.js.

So the following will work:

exports.onImageUpload = functions.storage.object().onFinalize(async (object) => {
    const storageRef = admin.storage().bucket(object.bucket);

    var metadata = {
        metadata: {
            'uploader': 'unknown'
        }
    }

    try {
        const setFileMetadataResponse = await storageRef.file(object.name).setMetadata(metadata);
        console.log('Success');
        console.log(setFileMetadataResponse[0]);
        return null;
    } catch (error) {
        console.log(error);
        return null;
    }
});