LoginSignup
5
3

More than 3 years have passed since last update.

firebaseのcloud storageの画像をfirestoreのデータ削除をトリガーに削除したい

Last updated at Posted at 2020-04-12

結論

下記のコードで案外簡単にできた。
ある特定のfirestoreのデータを削除するとそれに紐づく画像ファイルも消してほしかったので書いてみた。
firestoreとstorageがネストしている構造でも問題なく動作した。
firebase本当に素晴らしい!

※ 下記コードは一応TypeScriptで書かれています

import * as functions from 'firebase-functions';
import * as admin from "firebase-admin";
const firebase = admin.initializeApp();
// リージョン指定はお好みで
const tokyoRegion = "asia-northeast1";

// グループ削除をトリガーに紐づく画像ファイルを削除
export const deleteImageOnGroup = functions
         .region(tokyoRegion)
         .firestore.document("groups/{groupsDocId}")
         .onDelete((snap, context) => {
           const { groupsDocId } = context.params;
           const bucket = firebase.storage().bucket();

           return bucket.deleteFiles({
             prefix: `grpups/${groupsDocId}`
           });
         });

// アイテム削除をトリガーに紐づく画像ファイルを削除
export const deleteImageOnItem = functions
         .region(tokyoRegion)
         .firestore.document(
           "groups/{groupsDocId}/items/{itemsDocId}"
         )
         .onDelete((snap, context) => {
           const { groupsDocId, itemsDocId } = context.params;
           const bucket = firebase.storage().bucket();

           return bucket.deleteFiles({
             prefix: `groups/${groupsDocId}/items/${itemsDocId}`
           });
         });

ポイント

  • firestoreのonDeleteをトリガーにして発火させる
  • cloud storageの構成にfirestoreのドキュメントIDを使うことで判定できるようにする
  • onDeleteの引数からドキュメントIDを取得できるようにする

firestoreの命名

groups/{groupsDocId}/グループの各フィールド
groups/{groupsDocId}/items/{itemsDocId}/アイテムの各フィールド

cloud storageの命名

groups/{groupsDocId}/画像ファイル
groups/{groupsDocId}/items/{itemsDocId}/画像ファイル

参考

stackoverflow
Firebase function (written in NodeJS) to delete file from Cloud Storage when an object is removed from Realtime Database

medium
Automatically delete your Firebase Storage Files from Firestore with Cloud Functions for Firebase

5
3
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
5
3