【问题标题】:How to delete image stored in Firebase storage after triggering Firestore onDelete in Cloud Function?在 Cloud Function 中触发 Firestore onDelete 后如何删除存储在 Firebase 存储中的图像?
【发布时间】:2019-02-14 01:11:42
【问题描述】:

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

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

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

        const userID = context.params.userID

        // how to delete the image in here?





    });

我已尝试阅读文档,但我对如何实现该方法感到困惑:(。真的需要你的帮助。在此先感谢

【问题讨论】:

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


    【解决方案1】:

    以下 Cloud Function 代码将完成这项工作。

    // 改编自 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();
      });
    

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

    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 时,如果项目中只有一个(默认),则无需调出存储桶名称。此外,如果您发现错误,则仅记录错误是一种反模式。更正确的解决方案是只返回被拒绝的承诺,然后 Cloud Functions 将记录它。如果启用重试,它也会重试该功能。从 catch() 返回承诺将阻止重试系统工作。除非你真的做了一些处理错误的事情,否则最好返回被拒绝的错误。
    • 感谢您的宝贵建议@DougStevenson。因此,如果我理解正确返回 file.delete() 是正确的方法。 如果我没记错的话, CF 样本曾有一段时间使用return false; 捕获错误。我知道对于必须返回承诺的 CF,我们不再需要这样做了。
    • 是的,在这种情况下只返回承诺。我不记得官方样本的历史(不是我写的),但随着时间的推移,它们已经改进了。
    猜你喜欢
    • 1970-01-01
    • 2021-07-31
    • 2020-04-16
    • 2019-07-24
    • 2017-08-13
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多