如何编写一个函数来从Firestore中删除用户和从Storage中删除文件?

huangapple go评论67阅读模式
英文:

How to write a function that deletes user from Firestore and file from Storage?

问题

以下是翻译好的代码部分:

在我的应用中我允许用户撤销他们的访问权限所以当一个用户从 Firebase Authentication 中被删除时我有一个函数用来从 Firestore 中删除该用户

```javascript
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

exports.deleteUser = functions.auth.user().onDelete((user) => {
  const uid = user.uid;

  return admin
      .firestore()
      .collection("users")
      .doc(uid)
      .delete();
});

这段代码运行良好。问题是我想要删除存储在 Firebase Storage 中的个人资料图片,位置为:images/uid.png。所以,如何仅在图片存在时删除 Firestore 中的文档以及 Storage 中的图片呢?提前感谢您的回答。


<details>
<summary>英文:</summary>

In my app, I allow my users revoke their access. So when a user is deleted from the Firebase Authentication, I have a function that deletes the user from Firestore:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

exports.deleteUser = functions.auth.user().onDelete((user) => {
const uid = user.uid;

return admin
.firestore()
.collection("users")
.doc(uid)
.delete();
});


Which works fine. The problem is that I want to delete the profile picture that is stored in Firebase Storage at: `images/uid.png` as well. So how to delete the document in Firestore together with the image in Storage, **only if the image exists**? Thanks in advance.

</details>


# 答案1
**得分**: 4

您可以按以下方式使用Cloud Storage的Admin SDK([API文档][1]):

```javascript
exports.deleteUser = functions.auth.user().onDelete(async (user) => {

    try {
        const uid = user.uid;

        await admin
            .firestore()
            .collection("users")
            .doc(uid)
            .delete();

        const file = admin.storage().bucket().file(`images/${uid}.png`);
        const fileExists = await file.exists();
        if (fileExists) {
            await file.delete();    
        }
        
        return true;
        
    } catch (error) {
        console.log(error);
        return true;
    }
});

请注意,您还可以使用Delete User Data extension,该扩展专门用于此情况:“当用户删除其帐户时,从Cloud Firestore、实时数据库或Cloud Storage中删除以userId为键的数据。”

英文:

You can use the Admin SDK for Cloud Storage (API documentation) as follows:

exports.deleteUser = functions.auth.user().onDelete(async (user) =&gt; {

    try {
        const uid = user.uid;

        await admin
            .firestore()
            .collection(&quot;users&quot;)
            .doc(uid)
            .delete();

        const file = admin.storage().bucket().file(`images/${uid}.png`);
        const fileExists = await file.exists();
        if (fileExists) {
            await file.delete();    
        }
        
        return true;
        
    } catch (error) {
        console.log(error);
        return true;
    }
});

Note that you could also use the Delete User Data extension which is exactly done for this case: "Deletes data keyed on a userId from Cloud Firestore, Realtime Database, or Cloud Storage when a user deletes their account. "

答案2

得分: 2

Why don't you delete your picture with the user deletion?

exports.deleteUser = functions.auth.user().onDelete((user) => {
  const uid = user.uid;
  const picture = admin.storage().bucket().file(`images/${uid}.png`);

  return picture
    .exists()
    .then(() => imageRef.delete())
    .finally(() => admin.firestore().collection("users").doc(uid).delete());
});

Note, if the image doesn't exist, it will throw an error. But the finally will handle it properly in order to run the deletion.

英文:

Why don't you delete your picture with the user deletion?


exports.deleteUser = functions.auth.user().onDelete((user) =&gt; {
  const uid = user.uid;
  const picture = admin.storage().bucket().file(`images/${uid}.png`);

  return picture
    .exists()
    .then(() =&gt; imageRef.delete())
    .finally(() =&gt; admin.firestore().collection(&quot;users&quot;).doc(uid).delete());
});

Note, if the image doesn't exist, it will throw an error. But the finally will handle it properly in order to run the deletion.

huangapple
  • 本文由 发表于 2023年5月11日 17:02:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76225874.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定