简体   繁体   中英

Create a file in a cloud storage bucket from within a trigger

I would like to be able to create a file in a project Bucket as part of a Firestore cloud trigger.

When there is a change to a document on a specific collection I need to be able to take data from that document and write it to a file in a bucket in cloud storage Example

exports.myFunction = functions.firestore
  .document('documents/{docId}')
  .onUpdate((change, context) => {
    const after = change.after.data() as Document;
    // CREATE AND WRITE TO file IN BUCKET HERE
});

I have found many examples on how to upload files. I have explored

  • admin.storage().bucket().file(path)
  • createWriteStream()
  • write()

But I can't seem to find documentation on how exactly to achieve the above.

Is this possible from within a trigger and if so where can I find documentation on how to do this?

Here is why I want to do this (just in case I am approaching this all wrong) . We have an application where our users are able to generate purchase orders for work they have done. At the time they initiate a generate from the software we need to create a timestamped document [pdf] (in a secure location but on that is accessible to authenticated users) representing this purchase order. The data to create this will come from the document that triggers the change.

As @Doug Stevenson said, you can use node streams.

You can see how to do this in this sample from the GCP getting started samples repo . You need to provide a file name and the file buffer in order to stream it to GCS:

function sendUploadToGCS(req, res, next) {

  if (!req.file) {
    return next();
  }

  const gcsname = Date.now() + req.file.originalname;
  const file = bucket.file(gcsname);

  const stream = file.createWriteStream({
    metadata: {
      contentType: req.file.mimetype,
    },
    resumable: false,
  });

  stream.on('error', err => {
    req.file.cloudStorageError = err;
    next(err);
  });

  stream.on('finish', async () => {
    req.file.cloudStorageObject = gcsname;
    await file.makePublic();
    req.file.cloudStoragePublicUrl = getPublicUrl(gcsname);
    next();
  });

  stream.end(req.file.buffer);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM