【问题标题】:how to create refFromURL with admin privilege on cloud functions?如何在云功能上创建具有管理员权限的 refFromURL?
【发布时间】:2019-03-12 04:50:26
【问题描述】:

我想在触发firestore更新云功能时使用其http URL引用图像,以便我可以从onUpdate()函数提供的change获取url并使用它来获取对图像的引用firebase 存储并将其删除。

【问题讨论】:

  • 我认为你不需要文件的 URL 来做你想做的事情。通常您只需要存储桶和文件名。您是否想使用 URL 来识别文件,因为您的用户不知道任何其他标识符?此外,您是在谈论文件的“存储位置 URL”还是“下载 URL”?
  • 我说的是Http下载地址。

标签: firebase google-cloud-firestore google-cloud-functions firebase-storage


【解决方案1】:

要从 Cloud Function 中删除 Cloud Storage for Firebase 中存储的文件,您需要基于以下内容创建 File 对象:

  1. 此文件附加到的 Bucket 实例;

  2. 文件名,

然后调用delete()方法

详见 Node.js 库文档https://cloud.google.com/nodejs/docs/reference/storage/2.0.x/File

这是文档中的代码示例:

const storage = new Storage();
const bucketName = 'Name of a bucket, e.g. my-bucket';
const filename = 'File to delete, e.g. file.txt';

// Deletes the file from the bucket
storage
  .bucket(bucketName)
  .file(filename)
  .delete()
  .then(() => {
    console.log(`gs://${bucketName}/${filename} deleted.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

根据您的问题,我了解到您的应用程序客户端没有存储桶和文件名,只有一个下载 URL(如果它是一个网络应用程序,可能通过 getDownloadURL 生成,或者其他类似的方法SDK)。

因此,挑战是从下载 URL 派生存储桶和文件名。

如果你查看下载 URL 的格式,你会发现它的组成如下:

https://firebasestorage.googleapis.com/v0/b/<your-project-id>.appspot.com/o/<your-bucket-name>%2F<your-file-name>?alt=media&token=<a-token-string>

因此,您只需使用一组 Javascript 方法(如 indexOf()substring() 和/或 slice())从下载 URL 中提取存储桶和文件名。

根据上述情况,您的 Cloud Function 代码可能如下所示:

const storage = new Storage();

.....

exports.deleteStorageFile = functions.firestore
    .document('deletionRequests/{requestId}')
    .onUpdate((change, context) => {
      const newValue = change.after.data();
      const downloadUrl = newValue.downloadUrl;

      // extract the bucket and file names, for example through two dedicated Javascript functions
      const fileBucket = getFileBucket(downloadUrl);
      const fileName = getFileName(downloadUrl);

      return storage
        .bucket(fileBucket)
        .file(fileName)
        .delete()

    }); 

【讨论】:

  • 我目前正在这样做,我只是想看看是否有更有效的方法可以轻松创建参考。太奇怪了,Firebase 工程师还没有为此制作 api。无论如何,非常感谢@Renaud Tarnec
猜你喜欢
  • 2019-07-28
  • 2021-05-23
  • 1970-01-01
  • 2021-02-22
  • 2013-07-16
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多