The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Refactor error handling for storage mutations
Joshen Limf9c88b769f81
diff --git a/studio/components/interfaces/Storage/CreateBucketModal.tsx b/studio/components/interfaces/Storage/CreateBucketModal.tsxindex b636491841c..faea71d204b 100644--- a/studio/components/interfaces/Storage/CreateBucketModal.tsx+++ b/studio/components/interfaces/Storage/CreateBucketModal.tsx@@ -35,7 +35,7 @@ const CreateBucketModal = ({ visible, onClose }: CreateBucketModalProps) => {const { ref } = useParams()const router = useRouter()- const { mutateAsync: createBucket } = useBucketCreateMutation()+ const { mutateAsync: createBucket, isLoading: isCreating } = useBucketCreateMutation()const { data } = useProjectStorageConfigQuery({ projectRef: ref }, { enabled: IS_PLATFORM })const { value, unit } = convertFromBytes(data?.fileSizeLimit ?? 0)const formattedGlobalUploadLimit = `${value} ${unit}`@@ -63,38 +63,29 @@ const CreateBucketModal = ({ visible, onClose }: CreateBucketModalProps) => {return errors}- const onSubmit = async (values: any, { setSubmitting }: any) => {+ const onSubmit = async (values: any) => {if (!ref) return console.error('Project ref is required')- setSubmitting(true)- try {- const res = await createBucket({- projectRef: ref,- id: values.name,- isPublic: values.public,- file_size_limit: values.has_file_size_limit- ? convertToBytes(values.formatted_size_limit, selectedUnit)+ const res = await createBucket({+ projectRef: ref,+ id: values.name,+ isPublic: values.public,+ file_size_limit: values.has_file_size_limit+ ? convertToBytes(values.formatted_size_limit, selectedUnit)+ : null,+ allowed_mime_types:+ values.allowed_mime_types.length > 0+ ? values.allowed_mime_types.split(',').map((x: string) => x.trim()): null,- allowed_mime_types:- values.allowed_mime_types.length > 0- ? values.allowed_mime_types.split(',').map((x: string) => x.trim())- : null,- })+ })- ui.setNotification({- category: 'success',- message: `Successfully created bucket ${res.name}`,- })- router.push(`/project/${ref}/storage/buckets/${res.name}`)+ ui.setNotification({+ category: 'success',+ message: `Successfully created bucket ${res.name}`,+ })+ router.push(`/project/${ref}/storage/buckets/${res.name}`)- onClose()- } catch (error: any) {- ui.setNotification({- category: 'error',- message: `Failed to create bucket: ${error.message}`,- })- setSubmitting(false)- }+ onClose()}useEffect(() => {@@ -118,7 +109,7 @@ const CreateBucketModal = ({ visible, onClose }: CreateBucketModalProps) => {validate={validate}onSubmit={onSubmit}>- {({ values, isSubmitting }: { values: any; isSubmitting: boolean }) => {+ {({ values }: { values: any }) => {return (<div className="space-y-4 py-4"><Modal.Content>@@ -244,7 +235,7 @@ const CreateBucketModal = ({ visible, onClose }: CreateBucketModalProps) => {<Buttontype="default"htmlType="button"- disabled={isSubmitting}+ disabled={isCreating}onClick={() => onClose()}>Cancel@@ -252,8 +243,8 @@ const CreateBucketModal = ({ visible, onClose }: CreateBucketModalProps) => {<Buttontype="primary"htmlType="submit"- loading={isSubmitting}- disabled={isSubmitting}+ loading={isCreating}+ disabled={isCreating}>Save</Button>diff --git a/studio/components/interfaces/Storage/EditBucketModal.tsx b/studio/components/interfaces/Storage/EditBucketModal.tsxindex 2830fa9b4d0..272f30ac079 100644--- a/studio/components/interfaces/Storage/EditBucketModal.tsx+++ b/studio/components/interfaces/Storage/EditBucketModal.tsx@@ -34,7 +34,7 @@ const EditBucketModal = ({ visible, bucket, onClose }: EditBucketModalProps) =>const { ui } = useStore()const { ref } = useParams()- const { mutateAsync: updateBucket } = useBucketUpdateMutation()+ const { mutateAsync: updateBucket, isLoading: isUpdating } = useBucketUpdateMutation()const { data } = useProjectStorageConfigQuery({ projectRef: ref }, { enabled: IS_PLATFORM })const { value, unit } = convertFromBytes(data?.fileSizeLimit ?? 0)const formattedGlobalUploadLimit = `${value} ${unit}`@@ -50,35 +50,27 @@ const EditBucketModal = ({ visible, bucket, onClose }: EditBucketModalProps) =>return errors}- const onSubmit = async (values: any, { setSubmitting }: any) => {+ const onSubmit = async (values: any) => {if (bucket === undefined) return console.error('Bucket is required')if (ref === undefined) return console.error('Project ref is required')- try {- await updateBucket({- projectRef: ref,- id: bucket.id,- isPublic: values.public,- file_size_limit: values.has_file_size_limit- ? convertToBytes(values.formatted_size_limit, selectedUnit)+ await updateBucket({+ projectRef: ref,+ id: bucket.id,+ isPublic: values.public,+ file_size_limit: values.has_file_size_limit+ ? convertToBytes(values.formatted_size_limit, selectedUnit)+ : null,+ allowed_mime_types:+ values.allowed_mime_types.length > 0+ ? values.allowed_mime_types.split(',').map((x: string) => x.trim()): null,- allowed_mime_types:- values.allowed_mime_types.length > 0- ? values.allowed_mime_types.split(',').map((x: string) => x.trim())- : null,- })- ui.setNotification({- category: 'success',- message: `Successfully updated bucket "${bucket.name}"`,- })- onClose()- } catch (error: any) {- setSubmitting(false)- ui.setNotification({- category: 'success',- message: `Failed to update bucket: ${error.message}`,- })- }+ })+ ui.setNotification({+ category: 'success',+ message: `Successfully updated bucket "${bucket.name}"`,+ })+ onClose()}useEffect(() => {@@ -98,15 +90,7 @@ const EditBucketModal = ({ visible, bucket, onClose }: EditBucketModalProps) =>onCancel={onClose}><Form validateOnBlur={false} initialValues={{}} validate={validate} onSubmit={onSubmit}>- {({- values,- isSubmitting,- resetForm,- }: {- values: any- isSubmitting: boolean- resetForm: any- }) => {+ {({ values, resetForm }: { values: any; resetForm: any }) => {// [Alaister] although this "technically" is breaking the rules of React hooks// it won't error because the hooks are always rendered in the same order// eslint-disable-next-line react-hooks/rules-of-hooks@@ -260,14 +244,14 @@ const EditBucketModal = ({ visible, bucket, onClose }: EditBucketModalProps) =><div className="w-full border-t border-scale-500 !mt-0" /><Modal.Content><div className="flex items-center space-x-2 justify-end">- <Button type="default" disabled={isSubmitting} onClick={() => onClose()}>+ <Button type="default" disabled={isUpdating} onClick={() => onClose()}>Cancel</Button><Buttontype="primary"htmlType="submit"- loading={isSubmitting}- disabled={isSubmitting}+ loading={isUpdating}+ disabled={isUpdating}>Save</Button>diff --git a/studio/components/to-be-cleaned/Storage/DeleteBucketModal.tsx b/studio/components/to-be-cleaned/Storage/DeleteBucketModal.tsxindex bf17b863bbd..6a2945b9003 100644--- a/studio/components/to-be-cleaned/Storage/DeleteBucketModal.tsx+++ b/studio/components/to-be-cleaned/Storage/DeleteBucketModal.tsx@@ -1,6 +1,5 @@import { get as _get, find } from 'lodash'import { useRouter } from 'next/router'-import { useEffect, useState } from 'react'import { useParams } from 'common'import TextConfirmModal from 'components/ui/Modals/TextConfirmModal'@@ -20,55 +19,38 @@ const DeleteBucketModal = ({ visible = false, bucket, onClose }: DeleteBucketModconst { ui, meta } = useStore()const { ref: projectRef } = useParams()- const [deleting, setDeleting] = useState(false)const { data } = useBucketsQuery({ projectRef })- const { mutateAsync: deleteBucket } = useBucketDeleteMutation()+ const { mutateAsync: deleteBucket, isLoading: isDeleting } = useBucketDeleteMutation()const buckets = data ?? []- useEffect(() => {- setDeleting(false)- }, [visible])-const onDeleteBucket = async () => {if (!projectRef) return console.error('Project ref is required')- setDeleting(true)- try {- await deleteBucket({ projectRef, id: bucket.id })-- // Clean up policies from the corresponding bucket that was deleted- await meta.policies.loadBySchema('storage')- const policies = meta.policies.list()- const storageObjectsPolicies = policies.filter((policy) => policy.table === 'objects')- const formattedStorageObjectPolicies = formatPoliciesForStorage(- buckets,- storageObjectsPolicies- )- const bucketPolicies = _get(- find(formattedStorageObjectPolicies, { name: bucket.name }),- ['policies'],- []- )- await Promise.all(- bucketPolicies.map((policy: any) => {- meta.policies.del(policy.id)- })- )+ await deleteBucket({ projectRef, id: bucket.id })- ui.setNotification({- category: 'success',- message: `Successfully deleted bucket ${bucket.name}`,+ // Clean up policies from the corresponding bucket that was deleted+ await meta.policies.loadBySchema('storage')+ const policies = meta.policies.list()+ const storageObjectsPolicies = policies.filter((policy) => policy.table === 'objects')+ const formattedStorageObjectPolicies = formatPoliciesForStorage(buckets, storageObjectsPolicies)+ const bucketPolicies = _get(+ find(formattedStorageObjectPolicies, { name: bucket.name }),+ ['policies'],+ []+ )+ await Promise.all(+ bucketPolicies.map((policy: any) => {+ meta.policies.del(policy.id)})- router.push(`/project/${projectRef}/storage/buckets`)- onClose()- } catch (error: any) {- setDeleting(false)- ui.setNotification({- category: 'error',- message: `Failed to delete bucket: ${error.message}`,- })- }+ )++ ui.setNotification({+ category: 'success',+ message: `Successfully deleted bucket ${bucket.name}`,+ })+ router.push(`/project/${projectRef}/storage/buckets`)+ onClose()}return (@@ -79,7 +61,7 @@ const DeleteBucketModal = ({ visible = false, bucket, onClose }: DeleteBucketModonConfirm={onDeleteBucket}onCancel={onClose}confirmString={bucket.name}- loading={deleting}+ loading={isDeleting}text={<>Your bucket <span className="font-bold">{bucket.name}</span> and all its contents will bediff --git a/studio/data/storage/bucket-create-mutation.ts b/studio/data/storage/bucket-create-mutation.tsindex 3a70d4b0d73..56602c3b993 100644--- a/studio/data/storage/bucket-create-mutation.ts+++ b/studio/data/storage/bucket-create-mutation.ts@@ -1,6 +1,9 @@import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { toast } from 'react-hot-toast'+import { post } from 'lib/common/fetch'import { API_URL } from 'lib/constants'+import { ResponseError } from 'types'import { storageKeys } from './keys'export type BucketCreateVariables = {@@ -35,14 +38,15 @@ type BucketCreateData = Awaited<ReturnType<typeof createBucket>>export const useBucketCreateMutation = ({onSuccess,+ onError,...options}: Omit<- UseMutationOptions<BucketCreateData, unknown, BucketCreateVariables>,+ UseMutationOptions<BucketCreateData, ResponseError, BucketCreateVariables>,'mutationFn'> = {}) => {const queryClient = useQueryClient()- return useMutation<BucketCreateData, unknown, BucketCreateVariables>(+ return useMutation<BucketCreateData, ResponseError, BucketCreateVariables>((vars) => createBucket(vars),{async onSuccess(data, variables, context) {@@ -50,6 +54,13 @@ export const useBucketCreateMutation = ({await queryClient.invalidateQueries(storageKeys.buckets(projectRef))await onSuccess?.(data, variables, context)},+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to create bucket: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },...options,})diff --git a/studio/data/storage/bucket-delete-mutation.ts b/studio/data/storage/bucket-delete-mutation.tsindex f7b6fa701d0..399dcc20d1e 100644--- a/studio/data/storage/bucket-delete-mutation.ts+++ b/studio/data/storage/bucket-delete-mutation.ts@@ -1,6 +1,9 @@import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { toast } from 'react-hot-toast'+import { delete_, post } from 'lib/common/fetch'import { API_URL } from 'lib/constants'+import { ResponseError } from 'types'import { storageKeys } from './keys'export type BucketDeleteVariables = {@@ -24,14 +27,15 @@ type BucketDeleteData = Awaited<ReturnType<typeof deleteBucket>>export const useBucketDeleteMutation = ({onSuccess,+ onError,...options}: Omit<- UseMutationOptions<BucketDeleteData, unknown, BucketDeleteVariables>,+ UseMutationOptions<BucketDeleteData, ResponseError, BucketDeleteVariables>,'mutationFn'> = {}) => {const queryClient = useQueryClient()- return useMutation<BucketDeleteData, unknown, BucketDeleteVariables>(+ return useMutation<BucketDeleteData, ResponseError, BucketDeleteVariables>((vars) => deleteBucket(vars),{async onSuccess(data, variables, context) {@@ -39,6 +43,13 @@ export const useBucketDeleteMutation = ({await queryClient.invalidateQueries(storageKeys.buckets(projectRef))await onSuccess?.(data, variables, context)},+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to delete bucket: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },...options,})diff --git a/studio/data/storage/bucket-update-mutation.ts b/studio/data/storage/bucket-update-mutation.tsindex 7c14acac315..ec920849b1e 100644--- a/studio/data/storage/bucket-update-mutation.ts+++ b/studio/data/storage/bucket-update-mutation.ts@@ -1,6 +1,9 @@import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { toast } from 'react-hot-toast'+import { patch } from 'lib/common/fetch'import { API_URL } from 'lib/constants'+import { ResponseError } from 'types'import { storageKeys } from './keys'export type BucketUpdateVariables = {@@ -34,14 +37,15 @@ type BucketUpdateData = Awaited<ReturnType<typeof updateBucket>>export const useBucketUpdateMutation = ({onSuccess,+ onError,...options}: Omit<- UseMutationOptions<BucketUpdateData, unknown, BucketUpdateVariables>,+ UseMutationOptions<BucketUpdateData, ResponseError, BucketUpdateVariables>,'mutationFn'> = {}) => {const queryClient = useQueryClient()- return useMutation<BucketUpdateData, unknown, BucketUpdateVariables>(+ return useMutation<BucketUpdateData, ResponseError, BucketUpdateVariables>((vars) => updateBucket(vars),{async onSuccess(data, variables, context) {@@ -49,6 +53,13 @@ export const useBucketUpdateMutation = ({await queryClient.invalidateQueries(storageKeys.buckets(projectRef))await onSuccess?.(data, variables, context)},+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to update bucket: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },...options,})