Skip to content

Instantly share code, notes, and snippets.

@durchanek
Created August 8, 2019 14:10
Show Gist options
  • Select an option

  • Save durchanek/1d587e155855a67cc625a5ae39a3a517 to your computer and use it in GitHub Desktop.

Select an option

Save durchanek/1d587e155855a67cc625a5ae39a3a517 to your computer and use it in GitHub Desktop.
Node Google Cloud function for setting uploaded files cache-policy
/**
* Triggered from a change to a Cloud Storage bucket.
*
* @param {!Object} event Event payload.
* @param {!Object} context Metadata for the event.
*/
exports.setUploadedObjectMetadata = (event, context) => {
// Create a client
var storage = require('@google-cloud/storage')();
const data = event;
console.log(` Object finalized/created`);
console.log(` Bucket: ${data.bucket}`);
console.log(` Object: ${data.name}`);
console.log(` Created: ${data.timeCreated}`);
console.log(` Updated: ${data.updated}`);
if(data.name.substr(-1) === '/'){
console.log(` Skipping because ${data.name} is a directory`);
return;
}
const file = storage
.bucket(data.bucket)
.file(data.name);
// Update metadata
file.setMetadata({cacheControl: 'public, max-age=31536000'}).then(() => {
console.log(` Cache-Control updated successfully for ${data.name}`);
}).catch((e) => {
console.log(` There was an error setting Cache-Control for ${data.name}`);
console.log(e);
});
};
@durchanek
Copy link
Author

Google Storage sets cache expire to 1hr by default, which is not suitable when serving files that are public and not supposed to change (e.g. when using as storage for public CMS uploads). There is no simple way how to change this globally, but you can deploy this short Node function to Cloud Functions to set Cache-Control after upload to one year expire and public.

This function sets the policy for ALL objects - keep this in mind if you store files that are not supposed to be cached!

Use Google Cloud Functions Console to deploy the code with following settings:

Memory allocated: 128MB (can't imagine more could be needed)
Trigger: Cloud Storage
Event type: Finalize/Create
Runtime: Node 10
Function to execute: setUploadedObjectMetadata
Region: Closest possible
Retry on failure: Yes

In case the function fails for any reason, you can run this from the command line to mass set Cache-Control for all objects in the bucket:

gsutil -m setmeta -h "Cache-Control:public, max-age=31536000" gs://<STORAGE-BUCKET-NAME>/**/*.*

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment