LoginSignup
7
3

More than 3 years have passed since last update.

firebaseとfunctionsでstorageの画像ファイルを削除する

Last updated at Posted at 2020-07-06

画像ファイルのフォルダ以下一括削除

  1. usersコレクションのドキュメントの削除をトリガーに発火
  2. storageの構成をusers/{ドキュメントID}/{画像ファイル名}にしておく
  3. 削除されたドキュメントID以下すべてが削除される

backetのdeleteFilesを知りたければ下記を参考にする
https://googleapis.dev/nodejs/storage/latest/#deleteFiles


import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
const tokyoRegion = 'asia-northeast1'

// 環境変数の取得
const firebaseConfig: string|any = process.env.FIREBASE_CONFIG
const firebaseConfigObj: object|any = JSON.parse(firebaseConfig)
const bucket = admin.storage().bucket(firebaseConfigObj.storageBucket)

module.exports = functions
  .region(tokyoRegion)
  .firestore.document('users/{userDocId}')
  .onDelete((snap, context) => {
    const { userDocId } = context.params

    return bucket.deleteFiles({
      prefix: `users/${userDocId}`
    })
  })

特定の画像ファイルを削除

こちらのコードは動作確認していません。
要点は
1. 削除したいimagePathを指定
2. bucketの設定(複数個バケットがある場合)
3. bucket.file({filePath}).delete()で削除


import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
const tokyoRegion = 'asia-northeast1'

// 環境変数の取得
const firebaseConfig: string|any = process.env.FIREBASE_CONFIG
const firebaseConfigObj: object|any = JSON.parse(firebaseConfig)
const bucket = admin.storage().bucket(firebaseConfigObj.storageBucket)

module.exports = functions
  .region(tokyoRegion)
  .firestore.document('users/{userDocId}')
  .onDelete((snap, context) => {
    const { userDocId } = context.params
    const data = snap.after.data()

    // 何かしらで特定の削除する画像ファイルを指定
    const imagePath = data.imagePath

    return bucket.file(imagePath).delete()
  })

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