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

时间:2018-09-09 10:30:17

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

我想使用云功能后台触发器,因此,当我在Firestore中删除用户数据时,我也想删除其在Firebase存储中的个人资料图片。

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

enter image description here

enter image description here

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

        const userID = context.params.userID

        // how to delete the image in here?





    });

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

1 个答案:

答案 0 :(得分:1)

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

///根据道格的评论改编//

....
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