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 config mutations
Joshen Limeb1c05e9afaf
diff --git a/studio/components/interfaces/Settings/API/JWTSettings.tsx b/studio/components/interfaces/Settings/API/JWTSettings.tsxindex e93d4e12f74..2a88c19c004 100644--- a/studio/components/interfaces/Settings/API/JWTSettings.tsx+++ b/studio/components/interfaces/Settings/API/JWTSettings.tsx@@ -1,43 +1,41 @@-import { FC, useState, Dispatch, SetStateAction } from 'react'import * as Tooltip from '@radix-ui/react-tooltip'+import { PermissionAction } from '@supabase/shared-types/out/constants'+import {+ JwtSecretUpdateError,+ JwtSecretUpdateProgress,+ JwtSecretUpdateStatus,+} from '@supabase/shared-types/out/events'+import { Dispatch, SetStateAction, useState } from 'react'import {Alert,Button,Dropdown,- Input,- Modal,+ IconAlertCircle,+ IconChevronDown,IconEye,IconEyeOff,IconKey,IconLoader,- IconChevronDown,- IconRefreshCw,IconPenTool,- IconAlertCircle,+ IconRefreshCw,+ Input,+ Modal,} from 'ui'-import {- JwtSecretUpdateError,- JwtSecretUpdateProgress,- JwtSecretUpdateStatus,-} from '@supabase/shared-types/out/events'-import { PermissionAction } from '@supabase/shared-types/out/constants'-import { uuidv4 } from 'lib/helpers'-import { useStore, useCheckPermissions } from 'hooks'import { useParams } from 'common/hooks'-import { useJwtSecretUpdatingStatusQuery } from 'data/config/jwt-secret-updating-status-query'+import ConfirmModal from 'components/ui/Dialogs/ConfirmDialog'+import Panel from 'components/ui/Panel'import { useJwtSecretUpdateMutation } from 'data/config/jwt-secret-update-mutation'+import { useJwtSecretUpdatingStatusQuery } from 'data/config/jwt-secret-updating-status-query'import { useProjectPostgrestConfigQuery } from 'data/config/project-postgrest-config-query'+import { useCheckPermissions, useStore } from 'hooks'+import { uuidv4 } from 'lib/helpers'import {JWT_SECRET_UPDATE_ERROR_MESSAGES,JWT_SECRET_UPDATE_PROGRESS_MESSAGES,} from './API.constants'-import Panel from 'components/ui/Panel'-import ConfirmModal from 'components/ui/Dialogs/ConfirmDialog'--interface Props {}-const JWTSettings: FC<Props> = ({}) => {+const JWTSettings = () => {const { ui } = useStore()const { ref: projectRef } = useParams()@@ -45,8 +43,6 @@ const JWTSettings: FC<Props> = ({}) => {const [showCustomTokenInput, setShowCustomTokenInput] = useState(false)const [isCreatingKey, setIsCreatingKey] = useState<boolean>(false)const [isRegeneratingKey, setIsGeneratingKey] = useState<boolean>(false)- const [isSubmittingJwtSecretUpdateRequest, setIsSubmittingJwtSecretUpdateRequest] =- useState<boolean>(false)const canReadJWTSecret = useCheckPermissions(PermissionAction.READ, 'field.jwt_secret')const canGenerateNewJWTSecret = useCheckPermissions(@@ -56,6 +52,8 @@ const JWTSettings: FC<Props> = ({}) => {const { data } = useJwtSecretUpdatingStatusQuery({ projectRef })const { data: config, isError } = useProjectPostgrestConfigQuery({ projectRef })+ const { mutateAsync: updateJwt, isLoading: isSubmittingJwtSecretUpdateRequest } =+ useJwtSecretUpdateMutation()const { Failed, Updated, Updating } = JwtSecretUpdateStatus@@ -68,35 +66,21 @@ const JWTSettings: FC<Props> = ({}) => {const jwtSecretUpdateProgressMessage =JWT_SECRET_UPDATE_PROGRESS_MESSAGES[data?.jwtSecretUpdateProgress as JwtSecretUpdateProgress]- const { mutateAsync: updateJwt } = useJwtSecretUpdateMutation()-async function handleJwtSecretUpdate(jwt_secret: string,setModalVisibility: Dispatch<SetStateAction<boolean>>) {- if (!projectRef) return-- setIsSubmittingJwtSecretUpdateRequest(true)- try {- const trackingId = uuidv4()- await updateJwt({- projectRef,- jwtSecret: jwt_secret,- changeTrackingId: trackingId,- })+ if (!projectRef) return console.error('Project ref is required')- setModalVisibility(false)+ const trackingId = uuidv4()+ await updateJwt({ projectRef, jwtSecret: jwt_secret, changeTrackingId: trackingId })- ui.setNotification({- category: 'info',- message:- 'Successfully submitted JWT secret update request. Please wait while your project is updated.',- })- } catch (error: any) {- ui.setNotification({ category: 'error', message: error.message })- } finally {- setIsSubmittingJwtSecretUpdateRequest(false)- }+ setModalVisibility(false)+ ui.setNotification({+ category: 'info',+ message:+ 'Successfully submitted JWT secret update request. Please wait while your project is updated.',+ })}return (diff --git a/studio/components/interfaces/Settings/API/PostgrestConfig.tsx b/studio/components/interfaces/Settings/API/PostgrestConfig.tsxindex 1328b337b0f..0139feea6c3 100644--- a/studio/components/interfaces/Settings/API/PostgrestConfig.tsx+++ b/studio/components/interfaces/Settings/API/PostgrestConfig.tsx@@ -1,14 +1,14 @@-import { useContext, FC, useEffect } from 'react'+import { PermissionAction } from '@supabase/shared-types/out/constants'import { indexOf } from 'lodash'import { observer } from 'mobx-react-lite'-import { Input, Form, IconAlertCircle, InputNumber } from 'ui'-import { PermissionAction } from '@supabase/shared-types/out/constants'+import { useContext, useEffect } from 'react'+import { Form, IconAlertCircle, Input, InputNumber } from 'ui'-import { useCheckPermissions, useStore } from 'hooks'import { useParams } from 'common/hooks'+import MultiSelect from 'components/ui/MultiSelect'import { useProjectPostgrestConfigQuery } from 'data/config/project-postgrest-config-query'import { useProjectPostgrestConfigUpdateMutation } from 'data/config/project-postgrest-config-update-mutation'-import MultiSelect from 'components/ui/MultiSelect'+import { useCheckPermissions, useStore } from 'hooks'import { PageContext } from 'pages/project/[ref]/settings/api'import {@@ -19,50 +19,32 @@ import {FormSectionLabel,} from 'components/ui/Forms'-interface Props {}--const PostgrestConfig: FC<Props> = ({}) => {+const PostgrestConfig = () => {const PageState: any = useContext(PageContext)+ const { ref: projectRef } = useParams()const { ui } = useStore()const { meta } = PageState- const { ref: projectRef } = useParams()-- const formId = 'project-postgres-config'const { data: config, isError } = useProjectPostgrestConfigQuery({ projectRef })-- const initialValues = {- db_schema: '',- max_rows: '',- db_extra_search_path: '',- }-+ const { mutateAsync: updatePostgrestConfig } = useProjectPostgrestConfigUpdateMutation()const canUpdatePostgrestConfig = useCheckPermissions(PermissionAction.UPDATE,'custom_config_postgrest')- const { mutateAsync: updatePostgrestConfig } = useProjectPostgrestConfigUpdateMutation()+ const formId = 'project-postgres-config'+ const initialValues = { db_schema: '', max_rows: '', db_extra_search_path: '' }const updateConfig = async (updatedConfig: typeof initialValues) => {- if (!projectRef) return-- try {- await updatePostgrestConfig({- projectRef,- dbSchema: updatedConfig.db_schema,- maxRows: updatedConfig.max_rows,- dbExtraSearchPath: updatedConfig.db_extra_search_path,- })-- ui.setNotification({ category: 'success', message: 'Successfully saved settings' })- } catch (error: any) {- ui.setNotification({- error,- category: 'error',- message: `Failed to update config: ${error.message}`,- })- }+ if (!projectRef) return console.error('Project ref is required')++ await updatePostgrestConfig({+ projectRef,+ dbSchema: updatedConfig.db_schema,+ maxRows: updatedConfig.max_rows,+ dbExtraSearchPath: updatedConfig.db_extra_search_path,+ })+ ui.setNotification({ category: 'success', message: 'Successfully saved settings' })}const permanentSchema = ['public', 'storage']diff --git a/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsx b/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsxindex b7c73169bd3..4be77ab8168 100644--- a/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsx+++ b/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsx@@ -1,5 +1,10 @@import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'+import Link from 'next/link'+import { useState } from 'react'+import { Alert, Button, Form, InputNumber, Modal } from 'ui'+import { number, object } from 'yup'+import { useParams } from 'common/hooks'import { FormHeader } from 'components/ui/Forms'import Panel from 'components/ui/Panel'@@ -7,10 +12,6 @@ import { useProjectDiskResizeMutation } from 'data/config/project-disk-resize-muimport { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'import { useProjectUsageQuery } from 'data/usage/project-usage-query'import { useCheckPermissions, useStore } from 'hooks'-import Link from 'next/link'-import { useEffect, useState } from 'react'-import { Alert, Button, Form, InputNumber, Modal } from 'ui'-import { number, object } from 'yup'export interface DiskSizeConfigurationProps {disabled?: boolean@@ -20,38 +21,24 @@ const DiskSizeConfiguration = ({ disabled = false }: DiskSizeConfigurationProps)const { ui } = useStore()const { ref: projectRef } = useParams()- const canUpdateDiskSizeConfig = useCheckPermissions(PermissionAction.UPDATE, 'projects')-const [showResetDbPass, setShowResetDbPass] = useState<boolean>(false)- const [isUpdatingDiskSize, setIsUpdatingDiskSize] = useState<boolean>(false)+ const canUpdateDiskSizeConfig = useCheckPermissions(PermissionAction.UPDATE, 'projects')const { data: projectUsage } = useProjectUsageQuery({ projectRef })const { data: projectSubscriptionData } = useProjectSubscriptionV2Query({ projectRef })- const { mutateAsync: updateProjectUsage } = useProjectDiskResizeMutation()-- useEffect(() => {- if (showResetDbPass) {- setIsUpdatingDiskSize(false)- }- }, [showResetDbPass])+ const { mutateAsync: updateProjectUsage, isLoading: isUpdatingDiskSize } =+ useProjectDiskResizeMutation()const confirmResetDbPass = async (values: { [prop: string]: any }) => {const volumeSize = values['new-disk-size']- if (!projectRef) return+ if (!projectRef) return console.error('Project ref is required')- try {- setIsUpdatingDiskSize(true)- await updateProjectUsage({ projectRef, volumeSize })- ui.setNotification({- category: 'success',- message: `Successfully updated disk size to ${values['new-disk-size']} GB`,- })- setIsUpdatingDiskSize(false)- setShowResetDbPass(false)- } catch (error: any) {- ui.setNotification({ category: 'error', message: error.message })- setIsUpdatingDiskSize(false)- }+ await updateProjectUsage({ projectRef, volumeSize })+ ui.setNotification({+ category: 'success',+ message: `Successfully updated disk size to ${values['new-disk-size']} GB`,+ })+ setShowResetDbPass(false)}const currentDiskSize = projectUsage?.disk_volume_size_gb ?? 0diff --git a/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx b/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsxindex 6fe14d00574..d4f3c99dd98 100644--- a/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx+++ b/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx@@ -1,14 +1,14 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useState } from 'react'import { Button, Form, IconClock, Input, Listbox } from 'ui'-import { useCheckPermissions, useStore } from 'hooks'-import { IS_PLATFORM } from 'lib/constants'+import UpgradeToPro from 'components/ui/UpgradeToPro'import { useProjectStorageConfigQuery } from 'data/config/project-storage-config-query'import { useProjectStorageConfigUpdateUpdateMutation } from 'data/config/project-storage-config-update-mutation'-import UpgradeToPro from 'components/ui/UpgradeToPro'+import { useCheckPermissions, useStore } from 'hooks'+import { IS_PLATFORM } from 'lib/constants'+import { STORAGE_FILE_SIZE_LIMIT_MAX_BYTES, StorageSizeUnits } from './StorageSettings.constants'import { convertFromBytes, convertToBytes } from './StorageSettings.utils'-import { StorageSizeUnits, STORAGE_FILE_SIZE_LIMIT_MAX_BYTES } from './StorageSettings.constants'-import { PermissionAction } from '@supabase/shared-types/out/constants'export type StorageSettingsProps = {projectRef: string | undefined@@ -45,6 +45,7 @@ const StorageConfig = ({ config, projectRef }: any) => {let initialValues = { fileSizeLimit: value, unformattedFileSizeLimit: fileSizeLimit }const canUpdateStorageSettings = useCheckPermissions(PermissionAction.STORAGE_ADMIN_WRITE, '*')+ const { mutateAsync: updateStorageConfig } = useProjectStorageConfigUpdateUpdateMutation()const formattedMaxSizeBytes = `${new Intl.NumberFormat('en-US').format(STORAGE_FILE_SIZE_LIMIT_MAX_BYTES@@ -65,36 +66,26 @@ const StorageConfig = ({ config, projectRef }: any) => {return errors}- const { mutateAsync: updateStorageConfig } = useProjectStorageConfigUpdateUpdateMutation()-const onSubmit = async (values: any) => {const errors = onValidate(values)if (errors.fileSizeLimit) {- ui.setNotification({+ return ui.setNotification({category: 'error',message: `Upload file size limit must be up to 5GB (${formattedMaxSizeBytes})`,})- } else {- try {- const res = await updateStorageConfig({- projectRef,- fileSizeLimit: convertToBytes(values.fileSizeLimit, selectedUnit),- })-- const updatedValue = convertFromBytes(res.fileSizeLimit)- initialValues = {- fileSizeLimit: updatedValue.value,- unformattedFileSizeLimit: res.fileSizeLimit,- }- ui.setNotification({ category: 'success', message: 'Successfully updated settings' })- } catch (error: any) {- ui.setNotification({- category: 'error',- message: `Failed to update storage settings: ${error?.message}`,- })- }}++ const res = await updateStorageConfig({+ projectRef,+ fileSizeLimit: convertToBytes(values.fileSizeLimit, selectedUnit),+ })+ const updatedValue = convertFromBytes(res.fileSizeLimit)+ initialValues = {+ fileSizeLimit: updatedValue.value,+ unformattedFileSizeLimit: res.fileSizeLimit,+ }+ ui.setNotification({ category: 'success', message: 'Successfully updated storage settings' })}// [Joshen] To be refactored using FormContainer, FormPanel, FormContent etc oncediff --git a/studio/data/config/jwt-secret-update-mutation.ts b/studio/data/config/jwt-secret-update-mutation.tsindex 60706721f01..6d50154a832 100644--- a/studio/data/config/jwt-secret-update-mutation.ts+++ b/studio/data/config/jwt-secret-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 { configKeys } from './keys'export type JwtSecretUpdateVariables = {@@ -29,23 +32,29 @@ type JwtSecretUpdateData = Awaited<ReturnType<typeof updateJwtSecret>>export const useJwtSecretUpdateMutation = ({onSuccess,+ onError,...options}: Omit<- UseMutationOptions<JwtSecretUpdateData, unknown, JwtSecretUpdateVariables>,+ UseMutationOptions<JwtSecretUpdateData, ResponseError, JwtSecretUpdateVariables>,'mutationFn'> = {}) => {const queryClient = useQueryClient()- return useMutation<JwtSecretUpdateData, unknown, JwtSecretUpdateVariables>(+ return useMutation<JwtSecretUpdateData, ResponseError, JwtSecretUpdateVariables>((vars) => updateJwtSecret(vars),{async onSuccess(data, variables, context) {const { projectRef } = variables-await queryClient.invalidateQueries(configKeys.jwtSecretUpdatingStatus(projectRef))-await onSuccess?.(data, variables, context)},+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to submit JWT secret update request: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },...options,})diff --git a/studio/data/config/project-disk-resize-mutation.ts b/studio/data/config/project-disk-resize-mutation.tsindex 97a8b4e9a46..c07ca3245f1 100644--- a/studio/data/config/project-disk-resize-mutation.ts+++ b/studio/data/config/project-disk-resize-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 { usageKeys } from '../usage/keys'export type ProjectDiskResizeVariables = {@@ -30,30 +33,32 @@ type ProjectDiskResizeData = Awaited<ReturnType<typeof resizeProjectDisk>>export const useProjectDiskResizeMutation = ({onSuccess,+ onError,...options}: Omit<- UseMutationOptions<ProjectDiskResizeData, unknown, ProjectDiskResizeVariables>,+ UseMutationOptions<ProjectDiskResizeData, ResponseError, ProjectDiskResizeVariables>,'mutationFn'> = {}) => {const queryClient = useQueryClient()- return useMutation<ProjectDiskResizeData, unknown, ProjectDiskResizeVariables>(+ return useMutation<ProjectDiskResizeData, ResponseError, ProjectDiskResizeVariables>((vars) => resizeProjectDisk(vars),{async onSuccess(data, variables, context) {const { projectRef } = variables-- queryClient.setQueriesData(usageKeys.usage(projectRef), (prev) => {+ queryClient.setQueriesData(usageKeys.usage(projectRef), (prev: any) => {if (!prev) return prev-- return {- ...prev,- disk_volume_size_gb: variables.volumeSize,- }+ return { ...prev, disk_volume_size_gb: variables.volumeSize }})-await onSuccess?.(data, variables, context)},+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to resize project disk: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },...options,})diff --git a/studio/data/config/project-postgrest-config-update-mutation.ts b/studio/data/config/project-postgrest-config-update-mutation.tsindex ede88881f11..8b87c192ae2 100644--- a/studio/data/config/project-postgrest-config-update-mutation.ts+++ b/studio/data/config/project-postgrest-config-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 { configKeys } from './keys'export type ProjectPostgrestConfigUpdateVariables = {@@ -21,10 +24,8 @@ export async function updateProjectPostgrestConfig({max_rows: maxRows,db_extra_search_path: dbExtraSearchPath,})- if (response.error) {- throw response.error- }+ if (response.error) throw response.errorreturn response}@@ -32,11 +33,12 @@ type ProjectPostgrestConfigUpdateData = Awaited<ReturnType<typeof updateProjectPexport const useProjectPostgrestConfigUpdateMutation = ({onSuccess,+ onError,...options}: Omit<UseMutationOptions<ProjectPostgrestConfigUpdateData,- unknown,+ ResponseError,ProjectPostgrestConfigUpdateVariables>,'mutationFn'@@ -45,16 +47,21 @@ export const useProjectPostgrestConfigUpdateMutation = ({return useMutation<ProjectPostgrestConfigUpdateData,- unknown,+ ResponseError,ProjectPostgrestConfigUpdateVariables>((vars) => updateProjectPostgrestConfig(vars), {async onSuccess(data, variables, context) {const { projectRef } = variables-queryClient.invalidateQueries(configKeys.postgrest(projectRef))-await onSuccess?.(data, variables, context)},+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to update Postgrest config: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },...options,})}diff --git a/studio/data/config/project-storage-config-update-mutation.ts b/studio/data/config/project-storage-config-update-mutation.tsindex 8a9bf5e83b0..d1faba61008 100644--- a/studio/data/config/project-storage-config-update-mutation.ts+++ b/studio/data/config/project-storage-config-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 { configKeys } from './keys'export type ProjectStorageConfigUpdateUpdateVariables = {@@ -15,10 +18,7 @@ export async function updateProjectStorageConfigUpdate({const response = await patch(`${API_URL}/projects/${projectRef}/config/storage`, {fileSizeLimit,})- if (response.error) {- throw response.error- }-+ if (response.error) throw response.errorreturn response}@@ -28,11 +28,12 @@ type ProjectStorageConfigUpdateUpdateData = Awaited<export const useProjectStorageConfigUpdateUpdateMutation = ({onSuccess,+ onError,...options}: Omit<UseMutationOptions<ProjectStorageConfigUpdateUpdateData,- unknown,+ ResponseError,ProjectStorageConfigUpdateUpdateVariables>,'mutationFn'@@ -41,16 +42,21 @@ export const useProjectStorageConfigUpdateUpdateMutation = ({return useMutation<ProjectStorageConfigUpdateUpdateData,- unknown,+ ResponseError,ProjectStorageConfigUpdateUpdateVariables>((vars) => updateProjectStorageConfigUpdate(vars), {async onSuccess(data, variables, context) {const { projectRef } = variables-await queryClient.invalidateQueries(configKeys.storage(projectRef))-await onSuccess?.(data, variables, context)},+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to update storage settings: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },...options,})}