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