BucketFilePickerDialog.utils.tsx 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { QueryClient } from '@tanstack/react-query'
  2. import { toast } from 'sonner'
  3. import { storageKeys } from '@/data/storage/keys'
  4. import { createProjectBrivenClient } from '@/lib/project-briven-client'
  5. export async function uploadFilesToBucket({
  6. files,
  7. projectRef,
  8. hostEndpoint,
  9. bucketName,
  10. bucketId,
  11. currentPath,
  12. queryClient,
  13. }: {
  14. files: File[]
  15. projectRef: string
  16. hostEndpoint: string
  17. bucketName: string
  18. bucketId: string
  19. currentPath: string
  20. queryClient: QueryClient
  21. }) {
  22. if (files.length === 0) return
  23. const client = await createProjectBrivenClient(projectRef, hostEndpoint)
  24. let successCount = 0
  25. for (const file of files) {
  26. const filePath = currentPath ? `${currentPath}/${file.name}` : file.name
  27. const { error } = await client.storage.from(bucketName).upload(filePath, file, { upsert: true })
  28. if (error) {
  29. toast.error(`Failed to upload ${file.name}: ${error.message}`)
  30. } else {
  31. successCount++
  32. }
  33. }
  34. if (successCount > 0) {
  35. toast.success(`Successfully uploaded ${successCount} file${successCount > 1 ? 's' : ''}`)
  36. const queryKey = storageKeys.objects(projectRef, bucketId, '')
  37. await queryClient.refetchQueries({ queryKey, type: 'active' })
  38. }
  39. }