mirror of
https://github.com/supabase/supabase.git
synced 2026-09-22 13:37:53 +08:00
60 lines
1.7 KiB
TypeScript
60 lines
1.7 KiB
TypeScript
import { useMutation } from '@tanstack/react-query'
|
|
import { toast } from 'sonner'
|
|
|
|
import { components } from '@/data/api'
|
|
import { handleError, post } from '@/data/fetchers'
|
|
import type { ResponseError, UseCustomMutationOptions } from '@/types'
|
|
|
|
type BucketObjectPublicUrlParams = {
|
|
projectRef: string
|
|
bucketId?: string
|
|
path: string
|
|
options?: components['schemas']['GetSignedUrlBody']['options']
|
|
}
|
|
export const getPublicUrlForBucketObject = async (
|
|
{ projectRef, bucketId, path, options }: BucketObjectPublicUrlParams,
|
|
signal?: AbortSignal
|
|
) => {
|
|
if (!bucketId) throw new Error('bucketId is required')
|
|
|
|
const { data, error } = await post('/platform/storage/{ref}/buckets/{id}/objects/public-url', {
|
|
params: {
|
|
path: {
|
|
ref: projectRef,
|
|
id: bucketId,
|
|
},
|
|
},
|
|
body: { path, options },
|
|
signal,
|
|
})
|
|
|
|
if (error) handleError(error)
|
|
return data
|
|
}
|
|
|
|
type BucketObjectPublicUrlData = Awaited<ReturnType<typeof getPublicUrlForBucketObject>>
|
|
|
|
export const useGetBucketObjectPublicUrlMutation = ({
|
|
onSuccess,
|
|
onError,
|
|
...options
|
|
}: Omit<
|
|
UseCustomMutationOptions<BucketObjectPublicUrlData, ResponseError, BucketObjectPublicUrlParams>,
|
|
'mutationFn'
|
|
> = {}) => {
|
|
return useMutation<BucketObjectPublicUrlData, ResponseError, BucketObjectPublicUrlParams>({
|
|
mutationFn: (vars) => getPublicUrlForBucketObject(vars),
|
|
async onSuccess(data, variables, context) {
|
|
await onSuccess?.(data, variables, context)
|
|
},
|
|
async onError(data, variables, context) {
|
|
if (onError === undefined) {
|
|
toast.error(`Failed to get public URL of bucket object: ${data.message}`)
|
|
} else {
|
|
onError(data, variables, context)
|
|
}
|
|
},
|
|
...options,
|
|
})
|
|
}
|