0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

firestoreとcloudstorageのデータを一緒に削除したい + 保存時のファイル名が被らないようにしたい

Posted at

課題

storageを使って画像等を保存した際に、storeの方にURLなどのデータを保存したりしてる場合に
firestoreのデータを消した時、一緒にstorageの関連するデータを消したい。

storeデータの削除~取得から削除

import firebase from "../plugins/firebase";

export default class Images extends Vue {
  db = firebase.firestore();

//ここでstoreから取得
downLoad() {
    const imageList: any = [];
    this.db
      .collection("images")
      .orderBy("timeStamp", "desc")
      .limit(5)
      .get()
      .then((snapshot) => {
        snapshot.forEach((doc) => {
          imageList.push({ id: doc.id, data: doc.data() });//doc.idも保持しとく
        });
        this.images = imageList;//v-forを使って画面に表示するため
      });
  }

//storeからの削除
deleteStore(docId: string) {
    this.db
      .collection("images")
      .doc(docId)
      .delete()
      .then(() => {
        console.log("store削除完了");
        this.downLoad();
      });
}

これでstoreのデータは削除できるけど
これだとstorageのデータはそのままになる。

Storageからのデータ削除


//storageからの削除
  storage = firebase.storage();

  deleteStorage(fileName: string) {
    this.storage
      .ref()
      .child(`images/${fileName}`)
      .delete()
      .then(() => {
        console.log("storage削除完了");
      });
  }

これでstorageのデータの削除

storeとstorageから削除

上のメソッド二つを呼ぶだけ

deleteButton(docId: string, fileName: string) {
    this.deleteStore(docId);
    this.deleteStorage(fileName);
  }

これで無事に同時に削除されるようになりました。
でも問題が、、、ファイル名が同じやつは上書きされるんですね
アップロード時のファイル名をちょっといじる

修正

//時間を返すメソッドを作って
  getDate(): string {
    const time = new Date().getTime();
    return String(time);
  }

upLoad() {
    const time = this.getDate();//時間を文字列として取得
    const fileName = time + this.imageFile.name;//ファイル名と時間を繋げる
    const storageRef = this.storage.ref().child(`images/${fileName}`);//それをファイル名にする
    storageRef//storageへのアップロード処理
      .put(this.imageFile)
      .then(() => {
        storageRef.getDownloadURL().then((url) => {
          this.storeSave(url, fileName);//画像のURLとファイル名をストアに保存するメソッド呼び出し
        });
        this.imageFile = "";
        console.log("完了");
      })
      .catch(() => {
        alert("失敗しました");
      });
  }

 storeSave(imageUrl: string, fileName: string) {
    console.log(fileName);
    const user = this.auth.currentUser;//ユーザー情報の取得
    if (user === null) {
      return;
    }
    this.db
      .collection("images")
      .add({
        uid: user.uid,
        displayName: user.displayName,
        comment: this.comment,
        imageUrl: imageUrl,
        fileName: fileName,
        timeStamp: firebase.firestore.FieldValue.serverTimestamp(),
      })
      .then(() => {
        console.log("db完了");
        this.comment = "";
      });
  }

ファイル名+時間にすることでよっぽどアクセスが集中しない限りは
まず被ることはなくなったとおもいます。

最終的に

アップロードから削除までをまとめると


interface ImageList {
  id: string;
  data: {
    displayName: string;
    comment?: string;
    imageUrl?: string;
    fileName?: string;
    uid: string;
    timeStamp: {
      nanoseconds: number;
      seconds: number;
    };
  };
}
export default class Images extends Vue {
  storage = firebase.storage();
  db = firebase.firestore();
  auth = firebase.auth();
  images: ImageList[] = [];
  imageFile: any = "";
  comment: string | null = "";

//storageに保存
  saveStorage() {
    const time = this.getDate();
    const fileName = time + this.imageFile.name;
    const storageRef = this.storage.ref().child(`images/${fileName}`);
    storageRef
      .put(this.imageFile)
      .then(() => {
        storageRef.getDownloadURL().then((url) => {
          this.saveStore(url, fileName);//saveStoreへ
        });
        this.imageFile = "";
        console.log("stotage完了");
      })
      .catch(() => {
        alert("失敗しました");
      });
  }

//storeに保存
  saveStore(imageUrl: string, fileName: string) {
    const user = this.auth.currentUser;
    if (user === null) {
      return;
    }
    this.db
      .collection("images")
      .add({
        uid: user.uid,
        displayName: user.displayName,
        comment: this.comment,
        imageUrl: imageUrl,
        fileName: fileName,
        timeStamp: firebase.firestore.FieldValue.serverTimestamp(),
      })
      .then(() => {
        console.log("store完了");
        this.comment = "";
      })
      .catch(() => {
        alert("失敗しました");
      });
  }

//storeから取得
  downLoad() {
    const imageList: any = [];
    this.db
      .collection("images")
      .orderBy("timeStamp", "desc")
      .limit(5)
      .get()
      .then((snapshot) => {
        snapshot.forEach((doc) => {
          imageList.push({ id: doc.id, data: doc.data() });
        });
        this.images = imageList;
      });
  }

//削除
 deleteButton(docId: string, fileName: string) {
    this.deleteStore(docId);
    this.deleteStorage(fileName);
  }

//storeから削除
  deleteStore(docId: string) {
    this.db
      .collection("images")
      .doc(docId)
      .delete()
      .then(() => {
        console.log("store削除完了");
        this.downLoad();
      });
  }

//storageから削除
  deleteStorage(fileName: string) {
    this.storage
      .ref()
      .child(`images/${fileName}`)
      .delete()
      .then(() => {
        console.log("storage削除完了");
      });
  }
}

これでやりたかった事はひとまずできました。

間違いがあったらご指摘いただけるとうれしいです。

以上!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?