useFetchFileUrlQuery.tsx 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { useQuery } from '@tanstack/react-query'
  2. import { getPublicUrlForBucketObject } from '@/data/storage/bucket-object-get-public-url-mutation'
  3. import { signBucketObject } from '@/data/storage/bucket-object-sign-mutation'
  4. import { Bucket } from '@/data/storage/buckets-query'
  5. import type { ResponseError, UseCustomQueryOptions } from '@/types'
  6. const DEFAULT_EXPIRY = 7 * 24 * 60 * 60 // in seconds, default to 1 week
  7. export const fetchFileUrl = async (
  8. pathToFile: string,
  9. projectRef: string,
  10. bucketId: string,
  11. isBucketPublic: boolean,
  12. expiresIn?: number
  13. ) => {
  14. if (isBucketPublic) {
  15. const data = await getPublicUrlForBucketObject({
  16. projectRef: projectRef,
  17. bucketId: bucketId,
  18. path: pathToFile,
  19. })
  20. return data.publicUrl
  21. } else {
  22. const data = await signBucketObject({
  23. projectRef: projectRef,
  24. bucketId: bucketId,
  25. path: pathToFile,
  26. expiresIn: expiresIn ?? DEFAULT_EXPIRY,
  27. })
  28. return data.signedUrl
  29. }
  30. }
  31. type UseFileUrlQueryVariables = {
  32. path: string
  33. projectRef: string
  34. bucket: Bucket
  35. }
  36. export const useFetchFileUrlQuery = (
  37. { path, projectRef, bucket }: UseFileUrlQueryVariables,
  38. { ...options }: UseCustomQueryOptions<string, ResponseError> = {}
  39. ) => {
  40. return useQuery<string, ResponseError, string>({
  41. queryKey: [projectRef, 'buckets', bucket.public, bucket.id, 'file', path],
  42. queryFn: () => fetchFileUrl(path, projectRef, bucket.id, bucket.public, DEFAULT_EXPIRY),
  43. staleTime: DEFAULT_EXPIRY * 1000,
  44. ...options,
  45. })
  46. }