Created
August 8, 2019 14:10
-
-
Save durchanek/1d587e155855a67cc625a5ae39a3a517 to your computer and use it in GitHub Desktop.
Node Google Cloud function for setting uploaded files cache-policy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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); | |
| }); | |
| }; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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: