如何在 Cloud Function 中触发 Firestore onDelete 后删除存储在 Firebase 存储中的图像?

max*_*ano 5 google-cloud-storage firebase google-cloud-functions firebase-admin google-cloud-firestore

我想使用云函数后台触发器,所以当我在 Firestore 中删除用户数据时,我还想删除他们在 Firebase 存储中的个人资料图片。

userID 用作该图片的图像名称。并且图像位于 profilepicture 文件夹中

在此处输入图片说明

在此处输入图片说明

export const removeProfilePictureWhenDeletingUserData = functions.firestore
    .document('userss/{userID}')
    .onDelete((snap, context) => {

        const userID = context.params.userID

        // how to delete the image in here?





    });
Run Code Online (Sandbox Code Playgroud)

我试图阅读文档,但我对如何实现该方法感到困惑:(。真的需要你的帮助。提前致谢

Ren*_*nec 4

以下云功能代码将完成这项工作。

// 根据 Doug 在评论中的建议进行调整 //

....
const admin = require('firebase-admin');
admin.initializeApp();
....
var defaultStorage = admin.storage();

exports.removeProfilePictureWhenDeletingUserData = functions.firestore
  .document('users/{userID}')
  .onDelete((snap, context) => {
    const userID = context.params.userID;

    const bucket = defaultStorage.bucket();
    const file = bucket.file('profilePicture/' + userID + '.png');

    // Delete the file
    return file.delete();
  });
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅以下文档项目:

https://firebase.google.com/docs/reference/admin/node/admin.storage.Storage

https://cloud.google.com/nodejs/docs/reference/storage/1.7.x/File#delete

  • 在 Cloud Functions 中使用 Admin SDK 时,如果项目中只有一个(默认)存储桶名称,则无需调用存储桶名称。另外,如果发现错误就记录错误,这是一种反模式。更正确的解决方案是仅返回被拒绝的 Promise,然后 Cloud Functions 将记录它。如果启用重试,它也会重试该功能。从 catch() 返回承诺将阻止重试系统工作。最好返回被拒绝的错误,除非您确实已经采取了一些措施来处理该错误。 (3认同)