0
votes

Is there a way to set the cache-control metadata while putting a file to the Google Cloud Storage using Google Cloud Storage Adapter for Flysystem?

I have all my files in the bucket public, but sometimes I need to update some file, and after that I still see the old file. I see it's possible in general, but I don't see a way to do this by Flysystem, and we use it everywhere.

3

3 Answers

1
votes

Flysystem has ability to set adapter config. To set cache control header for GCP buckets, you can use next:

/** @var FilesystemInterface $storage */
$storage->put($path, $contents, [
    'metadata' => [
        'cacheControl' => 'no-cache,max-age=0'
     ]
]);

Also, you can setup Cloud Function in the GCP console to set headers when objects saved to the bucket

0
votes

You may find a PHP example of setting cache control in the reply to the Set Cache-Control php client on Google Cloud Storage Object.

0
votes

there are few ways to do this

  1. manually on GSC sonsole ("Edit Metadata" in each file) - bad solution if you have tons of files

  2. upload using gsutil

     gsutil -m -D -h Cache-Control:"Cache-Control:public, max-age=31536000" cp -r <path to your folder> gs://yourbucketname/optionalfolder/
    
  3. update meta reference

     gsutil -m setmeta -h "Content-Type:text/html" \
      -h "Cache-Control:public, max-age=3600" \
      -h "Content-Disposition" gs://bucket/*.html
    
  1. upload using API (PHP, Nodejs, Java, GO etc.) See SDK docs - there are alot of examples for each language.

  2. create Google Load Balancer and set custom meta field "Cache-Control" : "public, max-age=3600" in this case you will have your own CDN's domain name and flexible settings

  3. [best option] - create and deploy trigger script which will set meta (or anyting you want https://googleapis.dev/nodejs/storage/latest/File.html) right after upload (google.storage.object.finalize event)

create new folder with two files index.js and package.json

index.js

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

exports.prepare = (file, context) => {
   console.log("prepare: set cache control:" + file.name);
   storage.bucket(file.bucket).file(file.name).setMetadata({cacheControl: 'public, max-age=31536000'}); 
};

package.json

{
   "dependencies": {
        "@google-cloud/storage": ">=5.8.0"
   }
}

and deploy this function in two steps

  1. install and init cloud (https://cloud.google.com/sdk/docs/install)

     gcloud init
    
  2. deploy (it will ask to enable api first - follow instructions)

     gcloud functions deploy prepare \
      --runtime nodejs12 \
      --trigger-resource gs://yourbacketname \
      --trigger-event google.storage.object.finalize