Home > Software engineering >  firebase functions save the file to firebase storage
firebase functions save the file to firebase storage

Time:02-04

I am trying to generate a bundle in firebase functions and save it to firebase storage

exports.xyzUpdated = functions.firestore.document("xyz/{xyzID}").onWrite(async (change, context) => {
       const db = admin.firestore();
       const bucket = admin.storage().bucket("gs://xxx.appspot.com");// or empty or "xxx.appspot.com"
    
       const bundle = db.bundle(bundleName);
       const file = bucket.file(`bundles/${bundleName}.xyz`);
       const bundleBuffer = bundle.add(`queryName`, querySnapshot).build();
    
       await file.setMetadata({
              "Cache-Control": "public, max-age=86400, s-maxage=86400",
            });
    
       await file.save(bundleBuffer, {});
    });

I see an error in the cloud console:

Error: No such object: xxx.appspot.com/bundles/bundleName.xyz

What's wrong?

Thanks!

CodePudding user response:

You are trying to set metadata for a file before that is uploaded. Try changing the order of the statements as shown below:

await file.save(bundleBuffer, {});

await file.setMetadata({
  "Cache-Control": "public, max-age=86400, s-maxage=86400",
});

Alternatively, you can also set metadata while saving the file itself withouy setMetadata like this:

await file.save(bundleBuffer, {
  metadata: {
    cacheControl: "public, max-age=172800",
  }
});
  • Related