0

I want to delete some images triggered by FireStore's update. If a user delete images she registered, Firestore will update her post's URL's array.

Post URL in the array is like this.

http://192.168.1.5:9199/v0/b/example.appspot.com/o/post_images%2F1CA97725-5CF8-4C1B-AD70-674B19A2EE75

I developed the cloud functions to delete images comparing to the previous states using Admin SDK's TypeScript .

export const deletePostImages = functions
  .firestore.document("/posts/{postId}")
  .onUpdate(async (change, context) => {
    const oldData = change.before.data()
    const newData = change.after.data()

    
    const deletedImages = oldData.imageUrls.filter(
      (oldImage: string) => !newData.imageUrls.includes(oldImage)
    )

    const promises = deletedImages.map((url: string) => {
 
      const fileRef = admin.storage().bucket().file(url)
      return fileRef.delete()
    })
    await Promise.all(promises)
  })

But it seems the combination by my file path and bucket() is wrong.

The Error URL fileRef I got is here.

http://192.168.1.5:9199/b/example.appspot.com/o/192.168.1.5:9199/b/example.appspot.com/o/post_images%2F1CA97725-5CF8-4C1B-AD70-674B19A2EE75

I already read some docs like How to delete a file using Cloud Functions?

But I don't know how I should use bucket() and url in my context. How do I resolve it?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Takeshi
  • 59
  • 5

1 Answers1

0

You should only give the file location on your file() method instead of giving the full URL in it as the bucket() needs your bucket name and file() needs the object location in your bucket. e.g.:

const projectId = "your-project-id"
const objectPath = "your-object-path" // "post_images/2F1CA97725-5CF8-4C1B-AD70-674B19A2EE75"
const fileRef = admin.storage().bucket(`${projectId}.appspot.com`).file(`${objectPath}`)
return fileRef.delete()
Marc Anthony B
  • 3,635
  • 2
  • 4
  • 19