diff --git a/apps/docs/components/Navigation/NavigationMenu/MenuIcons.tsx b/apps/docs/components/Navigation/NavigationMenu/MenuIcons.tsx index 7306d2c55a286..dd0667b168479 100644 --- a/apps/docs/components/Navigation/NavigationMenu/MenuIcons.tsx +++ b/apps/docs/components/Navigation/NavigationMenu/MenuIcons.tsx @@ -684,7 +684,7 @@ export function IconUI({ width = 16, height = 16, className }: HomeMenuIcon) { height="14.72" rx="1.92" stroke="currentColor" - stroke-width="1.28" + strokeWidth="1.28" /> { const commands = useMemo( () => [ - { - id: 'support', - name: 'Support', - route: 'https://www.supabase.com/support', - icon: () => , - }, { id: 'system-status', - name: 'System Status', - value: 'Support: System Status', + name: 'View system status', + value: 'Support: View system status', route: 'https://status.supabase.com', + icon: () => , + }, + { + id: 'discord-community', + name: 'Ask Discord community', + value: 'Support: Ask Discord community', + route: 'https://discord.supabase.com', icon: () => , }, { - id: 'github-discussions', - name: 'GitHub Discussions', - value: 'Support: GitHub Discussions', - route: 'https://github.com/orgs/supabase/discussions', + id: 'support-team', + name: 'Contact support', + value: 'Support: Contact support', + route: 'https://www.supabase.com/support', icon: () => , - defaultHidden: true, }, ] as Array, [] diff --git a/apps/studio/components/interfaces/Auth/AuthTemplatesValidation.tsx b/apps/studio/components/interfaces/Auth/AuthTemplatesValidation.tsx index 390ba87c0e730..bf09377ebed02 100644 --- a/apps/studio/components/interfaces/Auth/AuthTemplatesValidation.tsx +++ b/apps/studio/components/interfaces/Auth/AuthTemplatesValidation.tsx @@ -9,7 +9,8 @@ const CONFIRMATION: FormSchema = { $schema: JSON_SCHEMA_VERSION, id: 'CONFIRMATION', type: 'object', - title: 'Confirm signup', + title: 'Confirm sign up', + purpose: 'Email verification for new user registrations', properties: { MAILER_SUBJECTS_CONFIRMATION: { title: 'Subject heading', @@ -20,7 +21,7 @@ const CONFIRMATION: FormSchema = { descriptionOptional: 'HTML body of your email', type: 'code', description: ` -- \`{{ .ConfirmationURL }}\` : URL to confirm the e-mail address for the new account +- \`{{ .ConfirmationURL }}\` : URL to confirm the email address for the new account - \`{{ .Token }}\` : The 6-digit numeric email OTP - \`{{ .TokenHash }}\` : The hashed token used in the URL - \`{{ .SiteURL }}\` : The URL of the site @@ -45,6 +46,7 @@ const INVITE: FormSchema = { id: 'INVITE', type: 'object', title: 'Invite user', + purpose: "Allows administrators to invite users who don't have accounts yet", properties: { MAILER_SUBJECTS_INVITE: { title: 'Subject heading', @@ -79,7 +81,8 @@ const MAGIC_LINK: FormSchema = { $schema: JSON_SCHEMA_VERSION, id: 'MAGIC_LINK', type: 'object', - title: 'Magic Link', + title: 'Magic link', + purpose: 'Passwordless login using email links', properties: { MAILER_SUBJECTS_MAGIC_LINK: { title: 'Subject heading', @@ -114,7 +117,8 @@ const EMAIL_CHANGE: FormSchema = { $schema: JSON_SCHEMA_VERSION, id: 'EMAIL_CHANGE', type: 'object', - title: 'Change Email Address', + title: 'Change email address', + purpose: 'Verification for email address changes', properties: { MAILER_SUBJECTS_EMAIL_CHANGE: { title: 'Subject heading', @@ -150,7 +154,8 @@ const RECOVERY: FormSchema = { $schema: JSON_SCHEMA_VERSION, id: 'RECOVERY', type: 'object', - title: 'Reset Password', + title: 'Reset password', + purpose: 'Password recovery flow for users who forgot their password', properties: { MAILER_SUBJECTS_RECOVERY: { title: 'Subject heading', @@ -185,6 +190,8 @@ const REAUTHENTICATION: FormSchema = { id: 'REAUTHENTICATION', type: 'object', title: 'Reauthentication', + purpose: + 'Additional verification for sensitive actions (like changing password, deleting account)', properties: { MAILER_SUBJECTS_REAUTHENTICATION: { title: 'Subject heading', diff --git a/apps/studio/components/interfaces/Auth/EmailRateLimitsAlert/EmailRateLimitsAlert.tsx b/apps/studio/components/interfaces/Auth/EmailRateLimitsAlert/EmailRateLimitsAlert.tsx index 86c6a517ba116..09ea5b0e90820 100644 --- a/apps/studio/components/interfaces/Auth/EmailRateLimitsAlert/EmailRateLimitsAlert.tsx +++ b/apps/studio/components/interfaces/Auth/EmailRateLimitsAlert/EmailRateLimitsAlert.tsx @@ -3,34 +3,28 @@ import Link from 'next/link' import { useParams } from 'common' import { InlineLink } from 'components/ui/InlineLink' import { DOCS_URL } from 'lib/constants' -import { - AlertDescription_Shadcn_, - AlertTitle_Shadcn_, - Alert_Shadcn_, - Button, - WarningIcon, -} from 'ui' +import { Button } from 'ui' +import { Admonition } from 'ui-patterns/admonition' export function EmailRateLimitsAlert() { const { ref } = useParams() return ( - - - Email rate-limits and restrictions - - You're using the built-in email service. The service has rate limits and it's not meant to - be used for production apps. Check the{' '} + +

+ You’re using the built-in email service. This service has rate limits and is not meant to be + used for production apps.{' '} - documentation + Learn more {' '} - for an up-to-date information on the current rate limits. - - - - - +

+ +
) } diff --git a/apps/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.tsx b/apps/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.tsx index 71b8164e6948e..1f5c9921a48bd 100644 --- a/apps/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.tsx +++ b/apps/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.tsx @@ -1,13 +1,26 @@ import { useParams } from 'common' +import { useIsSecurityNotificationsEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext' +import { ScaffoldSection } from 'components/layouts/Scaffold' import AlertError from 'components/ui/AlertError' import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader' import { useAuthConfigQuery } from 'data/auth/auth-config-query' -import { Card, Tabs_Shadcn_, TabsContent_Shadcn_, TabsList_Shadcn_, TabsTrigger_Shadcn_ } from 'ui' +import { ChevronRight } from 'lucide-react' +import Link from 'next/link' +import { + Card, + CardContent, + Tabs_Shadcn_, + TabsContent_Shadcn_, + TabsList_Shadcn_, + TabsTrigger_Shadcn_, +} from 'ui' import { TEMPLATES_SCHEMAS } from '../AuthTemplatesValidation' import EmailRateLimitsAlert from '../EmailRateLimitsAlert' +import { slugifyTitle } from './EmailTemplates.utils' import TemplateEditor from './TemplateEditor' export const EmailTemplates = () => { + const isSecurityNotificationsEnabled = useIsSecurityNotificationsEnabled() const { ref: projectRef } = useParams() const { data: authConfig, @@ -23,7 +36,7 @@ export const EmailTemplates = () => { (!authConfig.SMTP_HOST || !authConfig.SMTP_USER || !authConfig.SMTP_PASS) return ( -
+ {isError && ( {
) : null} - - - - {TEMPLATES_SCHEMAS.map((template) => { - return ( - - {template.title} - - ) - })} - + {isSecurityNotificationsEnabled ? ( + {TEMPLATES_SCHEMAS.map((template) => { - const panelId = template.title.trim().replace(/\s+/g, '-') + const templateSlug = slugifyTitle(template.title) return ( - - - + + +
+

{template.title}

+ {template.purpose && ( +

{template.purpose}

+ )} +
+ + +
) })} -
-
+ + ) : ( + + + + {TEMPLATES_SCHEMAS.map((template) => { + return ( + + {template.title} + + ) + })} + + {TEMPLATES_SCHEMAS.map((template) => { + const panelId = slugifyTitle(template.title) + return ( + + + + ) + })} + + + )} )} - + ) } diff --git a/apps/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.utils.ts b/apps/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.utils.ts new file mode 100644 index 0000000000000..e1297392939db --- /dev/null +++ b/apps/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.utils.ts @@ -0,0 +1,8 @@ +/** + * Convert template title to URL-friendly slug + * Shared function to ensure slug matching works correctly across multiple files + * Necessary because TEMPLATES_SCHEMAS does not provide a slug for each template + */ +export const slugifyTitle = (title: string) => { + return title.trim().replace(/\s+/g, '-').toLowerCase() +} diff --git a/apps/studio/components/interfaces/Organization/CloudMarketplace/cloud-marketplace-query.ts b/apps/studio/components/interfaces/Organization/CloudMarketplace/cloud-marketplace-query.ts index 0b9d924aa4c7e..359ee20aea595 100644 --- a/apps/studio/components/interfaces/Organization/CloudMarketplace/cloud-marketplace-query.ts +++ b/apps/studio/components/interfaces/Organization/CloudMarketplace/cloud-marketplace-query.ts @@ -42,9 +42,11 @@ export const useCloudMarketplaceOnboardingInfoQuery = = {} ) => { const { profile } = useProfile() - return useQuery( - cloudMarketplaceKeys.onboardingInfo(buyerId), - ({ signal }) => getCloudMarketplaceOnboardingInfo({ buyerId }, signal), - { enabled: enabled && profile !== undefined, ...options, staleTime: 30 * 60 * 1000 } - ) + return useQuery({ + queryKey: cloudMarketplaceKeys.onboardingInfo(buyerId), + queryFn: ({ signal }) => getCloudMarketplaceOnboardingInfo({ buyerId }, signal), + enabled: enabled && profile !== undefined, + ...options, + staleTime: 30 * 60 * 1000, + }) } diff --git a/apps/studio/components/interfaces/Organization/HeaderBanner.tsx b/apps/studio/components/interfaces/Organization/HeaderBanner.tsx index 9da5f4e65bda4..46dae901a5607 100644 --- a/apps/studio/components/interfaces/Organization/HeaderBanner.tsx +++ b/apps/studio/components/interfaces/Organization/HeaderBanner.tsx @@ -99,7 +99,7 @@ export const HeaderBanner = ({ {link && ( - View Details - + )} diff --git a/apps/studio/components/interfaces/Organization/NewProject/FreeProjectLimitWarning.tsx b/apps/studio/components/interfaces/Organization/NewProject/FreeProjectLimitWarning.tsx deleted file mode 100644 index 4aa43e5937ccc..0000000000000 --- a/apps/studio/components/interfaces/Organization/NewProject/FreeProjectLimitWarning.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { UpgradePlanButton } from 'components/ui/UpgradePlanButton' -import type { MemberWithFreeProjectLimit } from 'data/organizations/free-project-limit-check-query' -import { Admonition } from 'ui-patterns/admonition' - -interface FreeProjectLimitWarningProps { - membersExceededLimit: MemberWithFreeProjectLimit[] -} - -export const FreeProjectLimitWarning = ({ membersExceededLimit }: FreeProjectLimitWarningProps) => { - return ( - -

- The following members have reached their maximum limits for the number of active free - plan projects within organizations where they are an administrator or owner: -

-
    - {membersExceededLimit.map((member, idx: number) => ( -
  • - {member.username || member.primary_email} (Limit: {member.free_project_limit} free - projects) -
  • - ))} -
-

- These members will need to either delete, pause, or upgrade one or more of these - projects before you're able to create a free project within this organization. -

- - Upgrade plan - - } - /> - ) -} diff --git a/apps/studio/components/interfaces/Organization/NewProject/index.ts b/apps/studio/components/interfaces/Organization/NewProject/index.ts deleted file mode 100644 index a52ded23d6bcc..0000000000000 --- a/apps/studio/components/interfaces/Organization/NewProject/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { default as NotOrganizationOwnerWarning } from './NotOrganizationOwnerWarning' diff --git a/apps/studio/components/interfaces/ProjectCreation/AdvancedConfiguration.tsx b/apps/studio/components/interfaces/ProjectCreation/AdvancedConfiguration.tsx index 9ed6663b7c91e..18b4d4c5eb025 100644 --- a/apps/studio/components/interfaces/ProjectCreation/AdvancedConfiguration.tsx +++ b/apps/studio/components/interfaces/ProjectCreation/AdvancedConfiguration.tsx @@ -4,7 +4,6 @@ import { UseFormReturn } from 'react-hook-form' import { DocsButton } from 'components/ui/DocsButton' import Panel from 'components/ui/Panel' import { DOCS_URL } from 'lib/constants' -import { CreateProjectForm } from 'pages/new/[slug]' import { Badge, cn, @@ -19,6 +18,7 @@ import { } from 'ui' import { Admonition } from 'ui-patterns' import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' +import { CreateProjectForm } from './ProjectCreation.schema' interface AdvancedConfigurationProps { form: UseFormReturn diff --git a/apps/studio/components/interfaces/ProjectCreation/CloudProviderSelector.tsx b/apps/studio/components/interfaces/ProjectCreation/CloudProviderSelector.tsx new file mode 100644 index 0000000000000..92e6f70ea577b --- /dev/null +++ b/apps/studio/components/interfaces/ProjectCreation/CloudProviderSelector.tsx @@ -0,0 +1,63 @@ +import { UseFormReturn } from 'react-hook-form' + +import Panel from 'components/ui/Panel' +import { useCustomContent } from 'hooks/custom-content/useCustomContent' +import { PROVIDERS } from 'lib/constants' +import { + FormControl_Shadcn_, + FormField_Shadcn_, + Select_Shadcn_, + SelectContent_Shadcn_, + SelectGroup_Shadcn_, + SelectItem_Shadcn_, + SelectTrigger_Shadcn_, + SelectValue_Shadcn_, +} from 'ui' +import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' +import { CreateProjectForm } from './ProjectCreation.schema' + +interface CloudProviderSelectorProps { + form: UseFormReturn +} + +export const CloudProviderSelector = ({ form }: CloudProviderSelectorProps) => { + const { infraCloudProviders: validCloudProviders } = useCustomContent(['infra:cloud_providers']) + + return ( + + ( + + field.onChange(value)} + defaultValue={field.value} + > + + + + + + + + {Object.values(PROVIDERS) + .filter((provider) => validCloudProviders?.includes(provider.id) ?? true) + .map((providerObj) => { + const label = providerObj['name'] + const value = providerObj['id'] + return ( + + {label} + + ) + })} + + + + + )} + /> + + ) +} diff --git a/apps/studio/components/interfaces/ProjectCreation/ComputeSizeSelector.tsx b/apps/studio/components/interfaces/ProjectCreation/ComputeSizeSelector.tsx new file mode 100644 index 0000000000000..8797c7619d461 --- /dev/null +++ b/apps/studio/components/interfaces/ProjectCreation/ComputeSizeSelector.tsx @@ -0,0 +1,122 @@ +import { UseFormReturn } from 'react-hook-form' + +import { InlineLink } from 'components/ui/InlineLink' +import Panel from 'components/ui/Panel' +import { instanceSizeSpecs } from 'data/projects/new-project.constants' +import { getCloudProviderArchitecture } from 'lib/cloudprovider-utils' +import { DOCS_URL } from 'lib/constants' +import { CloudProvider } from 'shared-data' +import { + Badge, + FormField_Shadcn_, + Select_Shadcn_, + SelectContent_Shadcn_, + SelectGroup_Shadcn_, + SelectItem_Shadcn_, + SelectTrigger_Shadcn_, + SelectValue_Shadcn_, +} from 'ui' +import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' +import { sizes } from './ProjectCreation.constants' +import { CreateProjectForm } from './ProjectCreation.schema' + +interface ComputeSizeSelectorProps { + form: UseFormReturn +} + +export const ComputeSizeSelector = ({ form }: ComputeSizeSelectorProps) => { + return ( + + ( + +

+ The size for your dedicated database. You can change this later. Learn more about{' '} + + compute add-ons + {' '} + and{' '} + + compute billing + + . +

+ + } + > + field.onChange(value)}> + + + + + + {sizes + .filter((option) => + instanceSizeSpecs[option].cloud_providers.includes( + form.getValues('cloudProvider') as CloudProvider + ) + ) + .map((option) => { + return ( + +
+
+ + {instanceSizeSpecs[option].label} + +
+
+ + {instanceSizeSpecs[option].ram} RAM /{' '} + {instanceSizeSpecs[option].cpu}{' '} + {getCloudProviderArchitecture( + form.getValues('cloudProvider') as CloudProvider + )}{' '} + CPU + +

+ ${instanceSizeSpecs[option].priceHourly}/hour (~$ + {instanceSizeSpecs[option].priceMonthly}/month) +

+
+
+
+ ) + })} + +
+ Larger instance sizes available after creation +
+
+
+
+
+
+ )} + /> +
+ ) +} diff --git a/apps/studio/components/interfaces/ProjectCreation/CustomPostgresVersionInput.tsx b/apps/studio/components/interfaces/ProjectCreation/CustomPostgresVersionInput.tsx new file mode 100644 index 0000000000000..27e514e3dccd4 --- /dev/null +++ b/apps/studio/components/interfaces/ProjectCreation/CustomPostgresVersionInput.tsx @@ -0,0 +1,32 @@ +import { UseFormReturn } from 'react-hook-form' + +import Panel from 'components/ui/Panel' +import { FormControl_Shadcn_, FormField_Shadcn_, Input_Shadcn_ } from 'ui' +import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' +import { CreateProjectForm } from './ProjectCreation.schema' + +interface CustomPostgresVersionInputProps { + form: UseFormReturn +} + +export const CustomPostgresVersionInput = ({ form }: CustomPostgresVersionInputProps) => { + return ( + + ( + + + + + + )} + /> + + ) +} diff --git a/apps/studio/components/interfaces/ProjectCreation/DatabasePasswordInput.tsx b/apps/studio/components/interfaces/ProjectCreation/DatabasePasswordInput.tsx new file mode 100644 index 0000000000000..2777920390239 --- /dev/null +++ b/apps/studio/components/interfaces/ProjectCreation/DatabasePasswordInput.tsx @@ -0,0 +1,102 @@ +import { debounce } from 'lodash' +import { useRef } from 'react' +import { UseFormReturn } from 'react-hook-form' + +import Panel from 'components/ui/Panel' +import PasswordStrengthBar from 'components/ui/PasswordStrengthBar' +import passwordStrength from 'lib/password-strength' +import { generateStrongPassword } from 'lib/project' +import { FormControl_Shadcn_, FormField_Shadcn_ } from 'ui' +import { Input } from 'ui-patterns/DataInputs/Input' +import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' +import { DATABASE_PASSWORD_REGEX } from './ProjectCreation.constants' +import { CreateProjectForm } from './ProjectCreation.schema' +import { SpecialSymbolsCallout } from './SpecialSymbolsCallout' + +interface DatabasePasswordInputProps { + form: UseFormReturn + passwordStrengthMessage: string + setPasswordStrengthMessage: (value: string) => void + setPasswordStrengthWarning: (value: string) => void +} + +export const DatabasePasswordInput = ({ + form, + passwordStrengthMessage, + setPasswordStrengthMessage, + setPasswordStrengthWarning, +}: DatabasePasswordInputProps) => { + async function checkPasswordStrength(value: any) { + const { message, warning, strength } = await passwordStrength(value) + + form.setValue('dbPassStrength', strength) + form.trigger('dbPassStrength') + form.trigger('dbPass') + + setPasswordStrengthWarning(warning) + setPasswordStrengthMessage(message) + } + + const delayedCheckPasswordStrength = useRef( + debounce((value) => checkPasswordStrength(value), 300) + ).current + + // [Refactor] DB Password could be a common component used in multiple pages with repeated logic + function generatePassword() { + const password = generateStrongPassword() + form.setValue('dbPass', password) + delayedCheckPasswordStrength(password) + } + + return ( + + { + const isInvalidDatabasePassword = + field.value.length > 0 && !field.value.match(DATABASE_PASSWORD_REGEX) + + return ( + + {isInvalidDatabasePassword && } + + + } + > + + 0} + type="password" + placeholder="Type in a strong password" + {...field} + autoComplete="off" + onChange={async (event) => { + field.onChange(event) + form.trigger('dbPassStrength') + const value = event.target.value + if (event.target.value === '') { + await form.setValue('dbPassStrength', 0) + await form.trigger('dbPass') + } else { + await delayedCheckPasswordStrength(value) + } + }} + /> + + + ) + }} + /> + + ) +} diff --git a/apps/studio/components/interfaces/ProjectCreation/DisabledWarningDueToIncident.tsx b/apps/studio/components/interfaces/ProjectCreation/DisabledWarningDueToIncident.tsx new file mode 100644 index 0000000000000..e18d5efb3ad2b --- /dev/null +++ b/apps/studio/components/interfaces/ProjectCreation/DisabledWarningDueToIncident.tsx @@ -0,0 +1,31 @@ +import { AlertCircle } from 'lucide-react' + +import InformationBox from 'components/ui/InformationBox' +import Panel from 'components/ui/Panel' + +interface DisabledWarningDueToIncidentProps { + title: string +} + +export const DisabledWarningDueToIncident = ({ title }: DisabledWarningDueToIncidentProps) => { + return ( + + } + defaultVisibility={true} + hideCollapse + title={title} + description={ +
+

+ Our engineers are currently working on a fix. You can follow updates on{' '} + + https://status.supabase.com/ + +

+
+ } + /> +
+ ) +} diff --git a/apps/studio/components/interfaces/ProjectCreation/FreeProjectLimitWarning.tsx b/apps/studio/components/interfaces/ProjectCreation/FreeProjectLimitWarning.tsx new file mode 100644 index 0000000000000..00b5e33da992f --- /dev/null +++ b/apps/studio/components/interfaces/ProjectCreation/FreeProjectLimitWarning.tsx @@ -0,0 +1,41 @@ +import Panel from 'components/ui/Panel' +import { UpgradePlanButton } from 'components/ui/UpgradePlanButton' +import type { MemberWithFreeProjectLimit } from 'data/organizations/free-project-limit-check-query' +import { Admonition } from 'ui-patterns/admonition' + +interface FreeProjectLimitWarningProps { + membersExceededLimit: MemberWithFreeProjectLimit[] +} + +export const FreeProjectLimitWarning = ({ membersExceededLimit }: FreeProjectLimitWarningProps) => { + return ( + + +

+ The following members have reached their maximum limits for the number of active free + plan projects within organizations where they are an administrator or owner: +

+
    + {membersExceededLimit.map((member, idx: number) => ( +
  • + {member.username || member.primary_email} (Limit: {member.free_project_limit} free + projects) +
  • + ))} +
+

+ These members will need to either delete, pause, or upgrade one or more of these + projects before you're able to create a free project within this organization. +

+ + Upgrade plan + + } + /> +
+ ) +} diff --git a/apps/studio/components/interfaces/Organization/NewProject/NotOrganizationOwnerWarning.tsx b/apps/studio/components/interfaces/ProjectCreation/NotOrganizationOwnerWarning.tsx similarity index 88% rename from apps/studio/components/interfaces/Organization/NewProject/NotOrganizationOwnerWarning.tsx rename to apps/studio/components/interfaces/ProjectCreation/NotOrganizationOwnerWarning.tsx index a74dcafae7411..c08d172ebae3d 100644 --- a/apps/studio/components/interfaces/Organization/NewProject/NotOrganizationOwnerWarning.tsx +++ b/apps/studio/components/interfaces/ProjectCreation/NotOrganizationOwnerWarning.tsx @@ -6,7 +6,7 @@ interface NotOrganizationOwnerWarningProps { } // [Joshen] This can just use NoPermission component i think -const NotOrganizationOwnerWarning = ({ slug }: NotOrganizationOwnerWarningProps) => { +export const NotOrganizationOwnerWarning = ({ slug }: NotOrganizationOwnerWarningProps) => { return (
) } - -export default NotOrganizationOwnerWarning diff --git a/apps/studio/components/interfaces/ProjectCreation/OrganizationSelector.tsx b/apps/studio/components/interfaces/ProjectCreation/OrganizationSelector.tsx new file mode 100644 index 0000000000000..39c8b32a8d82e --- /dev/null +++ b/apps/studio/components/interfaces/ProjectCreation/OrganizationSelector.tsx @@ -0,0 +1,89 @@ +import { PermissionAction } from '@supabase/shared-types/out/constants' +import { useRouter } from 'next/router' +import { UseFormReturn } from 'react-hook-form' + +import { useParams } from 'common' +import Panel from 'components/ui/Panel' +import { useOrganizationsQuery } from 'data/organizations/organizations-query' +import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions' +import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization' +import { + Badge, + FormControl_Shadcn_, + FormField_Shadcn_, + Select_Shadcn_, + SelectContent_Shadcn_, + SelectGroup_Shadcn_, + SelectItem_Shadcn_, + SelectTrigger_Shadcn_, + SelectValue_Shadcn_, +} from 'ui' +import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' +import { OrgNotFound } from '../Organization/OrgNotFound' +import { NotOrganizationOwnerWarning } from './NotOrganizationOwnerWarning' +import { CreateProjectForm } from './ProjectCreation.schema' + +interface OrganizationSelectorProps { + form: UseFormReturn +} + +export const OrganizationSelector = ({ form }: OrganizationSelectorProps) => { + const router = useRouter() + const { slug } = useParams() + const { data: currentOrg } = useSelectedOrganizationQuery() + const { can: isAdmin } = useAsyncCheckPermissions(PermissionAction.CREATE, 'projects') + + const { data: organizations, isSuccess: isOrganizationsSuccess } = useOrganizationsQuery() + const isInvalidSlug = isOrganizationsSuccess && currentOrg === undefined + const orgNotFound = (organizations?.length ?? 0) > 0 && isInvalidSlug + + return ( + + {isAdmin && !isInvalidSlug && ( + ( + + {(organizations?.length ?? 0) > 0 && ( + { + field.onChange(slug) + router.push(`/new/${slug}`) + }} + value={field.value} + defaultValue={field.value} + > + + + + + + + + {organizations?.map((x) => ( + + {x.name} + {x.plan.name} + + ))} + + + + )} + + )} + /> + )} + + {isOrganizationsSuccess && !isAdmin && !orgNotFound && ( + + )} + {orgNotFound && } + + ) +} diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.constants.ts b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.constants.ts index 323ee0082d6ca..75ef67137abb8 100644 --- a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.constants.ts +++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.constants.ts @@ -1,3 +1,5 @@ +import { DesiredInstanceSize } from 'data/projects/new-project.constants' + // [Joshen] Obtained from https://gist.github.com/tadast/8827699 export const COUNTRY_LAT_LON = { AF: { lat: 33, lon: 65 }, @@ -253,4 +255,6 @@ export const COUNTRY_LAT_LON = { ZW: { lat: -20, lon: 30 }, } -export const SPECIAL_CHARS_REGEX = /^[^@:\/]*$/ +export const DATABASE_PASSWORD_REGEX = /^[^@:\/]*$/ + +export const sizes: DesiredInstanceSize[] = ['micro', 'small', 'medium'] diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.schema.ts b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.schema.ts new file mode 100644 index 0000000000000..334050a692813 --- /dev/null +++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.schema.ts @@ -0,0 +1,33 @@ +import { z } from 'zod' + +export const FormSchema = z.object({ + organization: z.string({ + required_error: 'Please select an organization', + }), + projectName: z + .string() + .trim() + .min(1, 'Please enter a project name.') // Required field check + .min(3, 'Project name must be at least 3 characters long.') // Minimum length check + .max(64, 'Project name must be no longer than 64 characters.'), // Maximum length check + postgresVersion: z.string({ + required_error: 'Please enter a Postgres version.', + }), + dbRegion: z.string({ + required_error: 'Please select a region.', + }), + cloudProvider: z.string({ + required_error: 'Please select a cloud provider.', + }), + dbPassStrength: z.number(), + dbPass: z + .string({ required_error: 'Please enter a database password.' }) + .min(1, 'Password is required.'), + instanceSize: z.string().optional(), + dataApi: z.boolean(), + useApiSchema: z.boolean(), + postgresVersionSelection: z.string(), + useOrioleDb: z.boolean(), +}) + +export type CreateProjectForm = z.infer diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.test.ts b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.test.ts index 289c047560469..6c8c546b97128 100644 --- a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.test.ts +++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.test.ts @@ -1,10 +1,10 @@ import { expect, test } from 'vitest' -import { SPECIAL_CHARS_REGEX } from './ProjectCreation.constants' +import { DATABASE_PASSWORD_REGEX } from './ProjectCreation.constants' test('Regex test to surface if password contains @, : or /', () => { - expect(!'teststring'.match(SPECIAL_CHARS_REGEX)).toEqual(false) - expect(!'test@string'.match(SPECIAL_CHARS_REGEX)).toEqual(true) - expect(!'te:ststring'.match(SPECIAL_CHARS_REGEX)).toEqual(true) - expect(!`tests/tring`.match(SPECIAL_CHARS_REGEX)).toEqual(true) - expect(!'!#$%^&*()'.match(SPECIAL_CHARS_REGEX)).toEqual(false) + expect(!'teststring'.match(DATABASE_PASSWORD_REGEX)).toEqual(false) + expect(!'test@string'.match(DATABASE_PASSWORD_REGEX)).toEqual(true) + expect(!'te:ststring'.match(DATABASE_PASSWORD_REGEX)).toEqual(true) + expect(!`tests/tring`.match(DATABASE_PASSWORD_REGEX)).toEqual(true) + expect(!'!#$%^&*()'.match(DATABASE_PASSWORD_REGEX)).toEqual(false) }) diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.ts b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.ts index 2db5478777f72..142542f318cc5 100644 --- a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.ts +++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.ts @@ -1,3 +1,4 @@ +import { DesiredInstanceSize, instanceSizeSpecs } from 'data/projects/new-project.constants' import type { CloudProvider, Region } from 'shared-data' import { AWS_REGIONS, FLY_REGIONS } from 'shared-data' import { SMART_REGION_TO_EXACT_REGION_MAP } from 'shared-data/regions' @@ -29,3 +30,17 @@ export function getAvailableRegions(cloudProvider: CloudProvider): Region { throw new Error('Invalid cloud provider') } } + +/** + * When launching new projects, they only get assigned a compute size once successfully launched, + * this might assume wrong compute size, but only for projects being rapidly launched after one another on non-default compute sizes. + * + * Needs to be in the API in the future [kevin] + */ +export const monthlyInstancePrice = (instance: string | undefined): number => { + return instanceSizeSpecs[instance as DesiredInstanceSize]?.priceMonthly || 10 +} + +export const instanceLabel = (instance: string | undefined): string => { + return instanceSizeSpecs[instance as DesiredInstanceSize]?.label || 'Micro' +} diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreationFooter.tsx b/apps/studio/components/interfaces/ProjectCreation/ProjectCreationFooter.tsx new file mode 100644 index 0000000000000..c64dd7795a5cb --- /dev/null +++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreationFooter.tsx @@ -0,0 +1,197 @@ +import { useRouter } from 'next/router' +import { UseFormReturn } from 'react-hook-form' + +import { LOCAL_STORAGE_KEYS, useFlag } from 'common' +import { InlineLink } from 'components/ui/InlineLink' +import { DesiredInstanceSize, instanceSizeSpecs } from 'data/projects/new-project.constants' +import { OrgProject } from 'data/projects/org-projects-infinite-query' +import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage' +import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization' +import { DOCS_URL } from 'lib/constants' +import { + Badge, + Button, + PopoverSeparator_Shadcn_, + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from 'ui' +import { InfoTooltip } from 'ui-patterns/info-tooltip' +import { CreateProjectForm } from './ProjectCreation.schema' +import { instanceLabel, monthlyInstancePrice } from './ProjectCreation.utils' + +interface ProjectCreationFooterProps { + form: UseFormReturn + canCreateProject: boolean + instanceSize?: string + organizationProjects: OrgProject[] + isCreatingNewProject: boolean + isSuccessNewProject: boolean +} + +export const ProjectCreationFooter = ({ + form, + canCreateProject, + instanceSize, + organizationProjects, + isCreatingNewProject, + isSuccessNewProject, +}: ProjectCreationFooterProps) => { + const router = useRouter() + const { data: currentOrg } = useSelectedOrganizationQuery() + const isFreePlan = currentOrg?.plan?.id === 'free' + + const projectCreationDisabled = useFlag('disableProjectCreationAndUpdate') + + const [lastVisitedOrganization] = useLocalStorageQuery( + LOCAL_STORAGE_KEYS.LAST_VISITED_ORGANIZATION, + '' + ) + + const availableComputeCredits = organizationProjects.length === 0 ? 10 : 0 + const additionalMonthlySpend = isFreePlan + ? 0 + : instanceSizeSpecs[instanceSize as DesiredInstanceSize]!.priceMonthly - availableComputeCredits + + // [kevin] This will eventually all be provided by a new API endpoint to preview and validate project creation, this is just for kaizen now + const monthlyComputeCosts = + // current project costs + organizationProjects.reduce((prev, acc) => { + const primaryDatabase = acc.databases.find((db) => db.identifier === acc.ref) + const cost = !!primaryDatabase ? monthlyInstancePrice(primaryDatabase.infra_compute_size) : 0 + return prev + cost + }, 0) + + // selected compute size + monthlyInstancePrice(instanceSize) - + // compute credits + 10 + + return ( +
+
+ {!isFreePlan && + !projectCreationDisabled && + canCreateProject && + additionalMonthlySpend > 0 && ( +
+ Additional costs +
+ ${additionalMonthlySpend}/m + +
+

+ Each project includes a dedicated Postgres instance running on its own server. + You are charged for the{' '} + + Compute resource + {' '} + of that server, independent of your database usage. +

+ {monthlyComputeCosts > 0 && ( +

Compute costs are applied on top of your subscription plan costs.

+ )} +
+ + + + + Project + Compute Size + Monthly Costs + + + + {organizationProjects.map((project) => { + const primaryDb = project.databases.find( + (db) => db.identifier === project.ref + ) + return ( + + {project.name} + + {instanceLabel(primaryDb?.infra_compute_size)} + + + ${monthlyInstancePrice(primaryDb?.infra_compute_size)} + + + ) + })} + + + + + {form.getValues('projectName') ?? 'New project'} + + + NEW + + + {instanceLabel(instanceSize)} + + ${monthlyInstancePrice(instanceSize)} + + + +
+ + + + + Compute Credits + + -$10 + + + + + + + Total Monthly Compute Costs + {/** + * API currently doesnt output replica information on the projects list endpoint. Until then, we cannot correctly calculate the costs including RRs. + * Will be adjusted in the future [kevin] + */} + {organizationProjects.length > 0 && ( +

+ Excluding Read replicas +

+ )} +
+ + ${monthlyComputeCosts} + +
+
+
+
+
+
+ )} +
+ +
+ + +
+
+ ) +} diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectNameInput.tsx b/apps/studio/components/interfaces/ProjectCreation/ProjectNameInput.tsx new file mode 100644 index 0000000000000..9d3be73eb22db --- /dev/null +++ b/apps/studio/components/interfaces/ProjectCreation/ProjectNameInput.tsx @@ -0,0 +1,28 @@ +import { UseFormReturn } from 'react-hook-form' + +import Panel from 'components/ui/Panel' +import { FormControl_Shadcn_, FormField_Shadcn_, Input_Shadcn_ } from 'ui' +import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' +import { CreateProjectForm } from './ProjectCreation.schema' + +interface ProjectNameInputProps { + form: UseFormReturn +} + +export const ProjectNameInput = ({ form }: ProjectNameInputProps) => { + return ( + + ( + + + + + + )} + /> + + ) +} diff --git a/apps/studio/components/interfaces/ProjectCreation/RegionSelector.tsx b/apps/studio/components/interfaces/ProjectCreation/RegionSelector.tsx index 7630a524b0be0..d7578686bc49c 100644 --- a/apps/studio/components/interfaces/ProjectCreation/RegionSelector.tsx +++ b/apps/studio/components/interfaces/ProjectCreation/RegionSelector.tsx @@ -1,7 +1,8 @@ -import { ControllerRenderProps } from 'react-hook-form' +import { UseFormReturn } from 'react-hook-form' import { useFlag, useParams } from 'common' import AlertError from 'components/ui/AlertError' +import Panel from 'components/ui/Panel' import { useDefaultRegionQuery } from 'data/misc/get-default-region-query' import { useOrganizationAvailableRegionsQuery } from 'data/organizations/organization-available-regions-query' import type { DesiredInstanceSize } from 'data/projects/new-project.constants' @@ -9,6 +10,7 @@ import { BASE_PATH, PROVIDERS } from 'lib/constants' import type { CloudProvider } from 'shared-data' import { Badge, + FormField_Shadcn_, SelectContent_Shadcn_, SelectGroup_Shadcn_, SelectItem_Shadcn_, @@ -23,11 +25,11 @@ import { cn, } from 'ui' import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' +import { CreateProjectForm } from './ProjectCreation.schema' import { getAvailableRegions } from './ProjectCreation.utils' interface RegionSelectorProps { - cloudProvider: CloudProvider - field: ControllerRenderProps + form: UseFormReturn instanceSize?: DesiredInstanceSize layout?: 'vertical' | 'horizontal' } @@ -37,12 +39,12 @@ interface RegionSelectorProps { // ^ can try again next time export const RegionSelector = ({ - cloudProvider, - field, + form, instanceSize, layout = 'horizontal', }: RegionSelectorProps) => { const { slug } = useParams() + const cloudProvider = form.getValues('cloudProvider') as CloudProvider const smartRegionEnabled = useFlag('enableSmartRegion') @@ -89,145 +91,164 @@ export const RegionSelector = ({ process.env.NEXT_PUBLIC_ENVIRONMENT === 'staging' const allSelectableRegions = [...smartRegions, ...regionOptions] - const selectedRegion = allSelectableRegions.find((region) => { - return !!region.name && region.name === field.value - }) if (isErrorAvailableRegions) { return } return ( - -

Select the region closest to your users for the best performance.

- {showNonProdFields && ( -
-

Only these regions are supported for local/staging projects:

-
    -
  • East US (North Virginia)
  • -
  • Central EU (Frankfurt)
  • -
  • Southeast Asia (Singapore)
  • -
-
- )} - - } - > - - - - {field.value !== undefined && ( -
- {selectedRegion?.code && ( - region icon - )} - {selectedRegion?.name ?? field.value} -
- )} -
-
- - {smartRegionEnabled && ( - <> - - Smart Region Selection - {smartRegions.map((value) => { - return ( - -
-
+ + { + const selectedRegion = allSelectableRegions.find((region) => { + return !!region.name && region.name === field.value + }) + + return ( + +

Select the region closest to your users for the best performance.

+ {showNonProdFields && ( +
+

Only these regions are supported for local/staging projects:

+
    +
  • East US (North Virginia)
  • +
  • Central EU (Frankfurt)
  • +
  • Southeast Asia (Singapore)
  • +
+
+ )} + + } + > + + + + {field.value !== undefined && ( +
+ {selectedRegion?.code && ( region icon - {value.name} -
- -
- {recommendedSmartRegions.has(value.code) && ( - - Recommended - - )} -
-
- - ) - })} - - - - )} - - - All Regions - {regionOptions.map((value) => { - return ( - :nth-child(2)]:w-full', - value.status !== undefined && '!pointer-events-auto' - )} - disabled={value.status !== undefined} - > -
-
- region icon -
- {value.name} - - {value.code} + )} + + {selectedRegion?.name ?? field.value}
-
- - {recommendedSpecificRegions.has(value.code) && ( - - Recommended - - )} - {value.status !== undefined && value.status === 'capacity' && ( - - - - Unavailable - - - - Temporarily unavailable due to this region being at capacity. - - )} -
-
- ) - })} -
- - - + + + + {smartRegionEnabled && ( + <> + + Smart Region Selection + {smartRegions.map((value) => { + return ( + +
+
+ region icon + {value.name} +
+ +
+ {recommendedSmartRegions.has(value.code) && ( + + Recommended + + )} +
+
+
+ ) + })} +
+ + + )} + + + All Regions + {regionOptions.map((value) => { + return ( + :nth-child(2)]:w-full', + value.status !== undefined && '!pointer-events-auto' + )} + disabled={value.status !== undefined} + > +
+
+ region icon +
+ {value.name} + + {value.code} + +
+
+ + {recommendedSpecificRegions.has(value.code) && ( + + Recommended + + )} + {value.status !== undefined && value.status === 'capacity' && ( + + + + Unavailable + + + + Temporarily unavailable due to this region being at capacity. + + + )} +
+
+ ) + })} +
+
+ + + ) + }} + /> + ) } diff --git a/apps/studio/components/interfaces/ProjectCreation/SecurityOptions.tsx b/apps/studio/components/interfaces/ProjectCreation/SecurityOptions.tsx index 7e13206a3a501..69fd74fed258e 100644 --- a/apps/studio/components/interfaces/ProjectCreation/SecurityOptions.tsx +++ b/apps/studio/components/interfaces/ProjectCreation/SecurityOptions.tsx @@ -2,7 +2,6 @@ import { ChevronRight } from 'lucide-react' import { UseFormReturn } from 'react-hook-form' import Panel from 'components/ui/Panel' -import { CreateProjectForm } from 'pages/new/[slug]' import { Badge, cn, @@ -17,6 +16,7 @@ import { } from 'ui' import { Admonition } from 'ui-patterns' import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' +import { CreateProjectForm } from './ProjectCreation.schema' interface SecurityOptionsProps { form: UseFormReturn diff --git a/apps/studio/components/interfaces/Realtime/RealtimeSettings.tsx b/apps/studio/components/interfaces/Realtime/RealtimeSettings.tsx index eb3d18eaa5220..13a8ec32d22d9 100644 --- a/apps/studio/components/interfaces/Realtime/RealtimeSettings.tsx +++ b/apps/studio/components/interfaces/Realtime/RealtimeSettings.tsx @@ -1,6 +1,5 @@ import { zodResolver } from '@hookform/resolvers/zod' import { PermissionAction } from '@supabase/shared-types/out/constants' -import Link from 'next/link' import { useState } from 'react' import { SubmitHandler, useForm } from 'react-hook-form' import { toast } from 'sonner' @@ -22,6 +21,7 @@ import { import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions' import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization' import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject' +import Link from 'next/link' import { Button, Card, @@ -68,7 +68,7 @@ export const RealtimeSettings = () => { const isFreePlan = organization?.plan.id === 'free' const isUsageBillingEnabled = organization?.usage_billing_enabled - const isRealtimeDisabed = data?.suspend ?? REALTIME_DEFAULT_CONFIG.suspend + const isRealtimeDisabled = data?.suspend ?? REALTIME_DEFAULT_CONFIG.suspend // Check if RLS policies exist for realtime.messages table const realtimeMessagesPolicies = policies?.filter( (policy) => policy.schema === 'realtime' && policy.table === 'messages' @@ -115,8 +115,10 @@ export const RealtimeSettings = () => { } as any, }) - const { allow_public } = form.watch() + const { allow_public, suspend } = form.watch() const isSettingToPrivate = !data?.private_only && !allow_public + const isDisablingRealtime = !isRealtimeDisabled && suspend + const isEnablingRealtime = isRealtimeDisabled && !suspend const onSubmit: SubmitHandler> = (data) => { if (!projectRef) return console.error('Project ref is required') @@ -167,7 +169,7 @@ export const RealtimeSettings = () => { { - {isSuccessOrganization && isRealtimeDisabed && ( - + {(isRealtimeDisabled || isDisablingRealtime || isEnablingRealtime) && ( +
- Realtime service is disabled + {isDisablingRealtime + ? 'Realtime service will be disabled' + : isEnablingRealtime + ? 'Realtime service will be re-enabled' + : isRealtimeDisabled + ? 'Realtime service is disabled' + : null}

- You will need to enable it to continue using Realtime + {isDisablingRealtime + ? 'Clients will no longer be able to connect to your project’s realtime service once saved' + : isEnablingRealtime + ? "Clients will be able to connect to your project's realtime service again once saved" + : isRealtimeDisabled + ? 'You will need to enable it to continue using Realtime' + : null}

@@ -197,450 +216,342 @@ export const RealtimeSettings = () => { )} /> - - ( - Channel restrictions} - > - - + + ( + Channel restrictions} > - - - - + + + + + + - {isSuccessPolicies && - !hasRealtimeMessagesPolicies && - !allow_public && - !isRealtimeDisabed && ( - -

- Private mode is {isSettingToPrivate ? 'being ' : ''} - enabled, but no RLS policies exists on the{' '} - realtime.messages table. No - messages will be received by users. -

+ {isSuccessPolicies && + !hasRealtimeMessagesPolicies && + !allow_public && + !isRealtimeDisabled && ( + +

+ Private mode is {isSettingToPrivate ? 'being ' : ''} + enabled, but no RLS policies exists on the{' '} + realtime.messages table. + No messages will be received by users. +

- - + + + } + /> + )} +
+
+ )} + /> +
+ + ( + + Realtime Authorization uses this database pool to check client + access +

} - /> - )} - -
- )} - /> -
- - ( - - Realtime Authorization uses this database pool to check client - access -

+ > + Database connection pool size + } > - Database connection pool size - - } - > - - - - - - {!!maxConn && field.value > maxConn.maxConnections * 0.5 && ( - - )} - -
- )} - /> -
- - ( - - Sets maximum number of concurrent clients that can connect to your - Realtime service -

+ + + + + + {!!maxConn && field.value > maxConn.maxConnections * 0.5 && ( + + )} + +
+ )} + /> +
+ + ( + + Sets maximum number of concurrent clients that can connect to + your Realtime service +

+ } + > + Max concurrent clients + } > - Max concurrent clients - - } - > - - - - - - -
- )} - /> -
- - ( - - Sets maximum number of events per second that can be sent to your - Realtime service -

+ + + + + + +
+ )} + /> +
+ + ( + + Sets maximum number of events per second that can be sent to + your Realtime service +

+ } + > + Max events per second + } > - Max events per second - - } - > - - - - - - {isSuccessOrganization && - !isUsageBillingEnabled && - !isRealtimeDisabed && ( - -
-
-
- Spend cap needs to be disabled to configure this value -
-

- {isFreePlan - ? 'Upgrade to the Pro plan first to disable spend cap' - : 'You may adjust this setting in the organization billing settings'} -

+ + + + + + {isSuccessOrganization && !isUsageBillingEnabled && ( + +
+
+
+ Spend cap needs to be disabled to configure this value +
+

+ {isFreePlan + ? 'Upgrade to the Pro plan first to disable spend cap' + : 'You may adjust this setting in the organization billing settings'} +

+
+
+ {isFreePlan ? ( + + ) : ( + + )} +
-
- {isFreePlan ? ( - - ) : ( - - )} -
-
- - )} - - - )} - /> - - - ( - - Sets maximum number of presence events per second that can be sent - to your Realtime service -

+ + )} + +
+ )} + /> +
+ + ( + + Sets maximum number of presence events per second that can be + sent to your Realtime service +

+ } + > + Max presence events per second + } > - Max presence events per second - - } - > - - - - - - {isSuccessOrganization && - !isUsageBillingEnabled && - !isRealtimeDisabed && ( - -
-
-
- Spend cap needs to be disabled to configure this value -
-

- {isFreePlan - ? 'Upgrade to the Pro plan first to disable spend cap' - : 'You may adjust this setting in the organization billing settings'} -

+ + + + + + {isSuccessOrganization && !isUsageBillingEnabled && ( + +
+
+
+ Spend cap needs to be disabled to configure this value +
+

+ {isFreePlan + ? 'Upgrade to the Pro plan first to disable spend cap' + : 'You may adjust this setting in the organization billing settings'} +

+
+
+ {isFreePlan ? ( + + ) : ( + + )} +
-
- {isFreePlan ? ( - - ) : ( - - )} -
-
- - )} - - - )} - /> - - - ( - - Sets maximum number of payload size in KB that can be sent to your - Realtime service -

+ + )} + +
+ )} + /> +
+ + ( + + Sets maximum number of payload size in KB that can be sent to + your Realtime service +

+ } + > + Max payload size in KB + } > - Max payload size in KB - - } - > - - - - - - {isSuccessOrganization && - !isUsageBillingEnabled && - !isRealtimeDisabed && ( - -
-
-
- Spend cap needs to be disabled to configure this value -
-

- {isFreePlan - ? 'Upgrade to the Pro plan first to disable spend cap' - : 'You may adjust this setting in the organization billing settings'} -

+ + + + + + {isSuccessOrganization && !isUsageBillingEnabled && ( + +
+
+
+ Spend cap needs to be disabled to configure this value +
+

+ {isFreePlan + ? 'Upgrade to the Pro plan first to disable spend cap' + : 'You may adjust this setting in the organization billing settings'} +

+
+
+ {isFreePlan ? ( + + ) : ( + + )} +
-
- {isFreePlan ? ( - - ) : ( - - )} -
-
- - )} - - - )} - /> - - - {/* - [Joshen] The following fields are hidden from the UI temporarily while we figure out what settings to expose to the users - - Max bytes per second - - Max channels per client - - Max joins per second - */} - - {/* - { - const { value, unit } = convertFromBytes(field.value ?? 0) - return ( - - Sets maximum number of bytes per second rate per channel limit -

- } - > - Max bytes per second - - } - > - - - - - - {!!field.value ? ( - - This is equivalent to {value.toFixed(2)} {unit} - - ) : null} - -
- ) - }} - /> -
*/} - {/* - ( - - Sets maximum number of channels per client rate limit -

- } - > - Max channels per client - - } - > - - - - - - -
- )} - /> -
*/} - {/* - ( - - Sets maximum number of joins per second rate limit -

- } - > - Max joins per second - - } - > - - - - - - -
- )} - /> -
*/} + + )} + + + )} + /> + + + )}
diff --git a/apps/studio/components/interfaces/Reports/v2/ReportChartV2.tsx b/apps/studio/components/interfaces/Reports/v2/ReportChartV2.tsx index b84e320db062f..769ee3b4bacba 100644 --- a/apps/studio/components/interfaces/Reports/v2/ReportChartV2.tsx +++ b/apps/studio/components/interfaces/Reports/v2/ReportChartV2.tsx @@ -78,22 +78,20 @@ export const ReportChartV2 = ({ isLoading: isLoadingChart, error, isFetching, - } = useQuery( - [ + } = useQuery({ + queryKey: [ 'projects', projectRef, 'report-v2', { reportId: report.id, startDate, endDate, interval, filters }, ], - async () => { + queryFn: async () => { return await report.dataProvider(projectRef, startDate, endDate, interval, filters) }, - { - enabled: Boolean(projectRef && canFetch && isAvailable && !report.hide), - refetchOnWindowFocus: false, - staleTime: 0, - } - ) + enabled: Boolean(projectRef && canFetch && isAvailable && !report.hide), + refetchOnWindowFocus: false, + staleTime: 0, + }) const chartData = queryResult?.data || [] const dynamicAttributes = queryResult?.attributes || [] diff --git a/apps/studio/components/interfaces/Settings/General/General.tsx b/apps/studio/components/interfaces/Settings/General/General.tsx index 61c0f7d22364a..fb8b87e4d5407 100644 --- a/apps/studio/components/interfaces/Settings/General/General.tsx +++ b/apps/studio/components/interfaces/Settings/General/General.tsx @@ -1,6 +1,7 @@ import { PermissionAction } from '@supabase/shared-types/out/constants' import { BarChart2 } from 'lucide-react' import Link from 'next/link' +import { useState } from 'react' import { toast } from 'sonner' import { FormActions } from 'components/ui/Forms/FormActions' @@ -30,6 +31,9 @@ const General = () => { const { data: project } = useSelectedProjectQuery() const { data: organization } = useSelectedOrganizationQuery() + // [Joshen] Need to refactor to use RHF so we don't need manual error handlers like this + const [nameError, setNameError] = useState() + const { data: parentProject } = useProjectDetailQuery({ ref: project?.parent_project_ref }) const isBranch = parentProject !== undefined @@ -50,6 +54,11 @@ const General = () => { const onSubmit = async (values: any, { resetForm }: any) => { if (!project?.ref) return console.error('Ref is required') + if (values.name.length < 3) { + setNameError('Project name must be at least 3 characters long') + return + } + updateProject( { ref: project.ref, name: values.name.trim() }, { @@ -95,7 +104,10 @@ const General = () => { form={formId} isSubmitting={isUpdating} hasChanges={hasChanges} - handleReset={handleReset} + handleReset={() => { + handleReset() + setNameError(undefined) + }} helper={ !canUpdateProject ? "You need additional permissions to manage this project's settings" @@ -112,6 +124,8 @@ const General = () => { size="small" label="Project name" disabled={isBranch || !canUpdateProject} + onChange={() => setNameError(undefined)} + error={nameError} /> diff --git a/apps/studio/components/interfaces/Storage/StorageMenu.BucketList.tsx b/apps/studio/components/interfaces/Storage/StorageMenu.BucketList.tsx index b49c691a71f6b..c2d0193ce3d97 100644 --- a/apps/studio/components/interfaces/Storage/StorageMenu.BucketList.tsx +++ b/apps/studio/components/interfaces/Storage/StorageMenu.BucketList.tsx @@ -4,6 +4,7 @@ import type { ListChildComponentProps } from 'react-window' import { FixedSizeList as List, areEqual } from 'react-window' import type { Bucket } from 'data/storage/buckets-query' +import { cn } from 'ui' import { BucketRow } from './BucketRow' type BucketListProps = { @@ -25,7 +26,7 @@ const VirtualizedBucketRow = memo( isSelected={isSelected} projectRef={data.projectRef} style={style as CSSProperties} - className={BUCKET_ROW_HEIGHT} + className={cn(BUCKET_ROW_HEIGHT)} /> ) }, @@ -95,19 +96,15 @@ export const BucketList = ({ buckets, selectedBucketId, projectRef = '' }: Bucke const numBuckets = buckets.length if (numBuckets <= 50) { - return ( -
- {buckets.map((bucket) => ( - - ))} -
- ) + return buckets.map((bucket) => ( + + )) } return ( diff --git a/apps/studio/components/interfaces/Storage/StorageMenu.tsx b/apps/studio/components/interfaces/Storage/StorageMenu.tsx index 8ffd4ca64e6c8..0ee63944eb88e 100644 --- a/apps/studio/components/interfaces/Storage/StorageMenu.tsx +++ b/apps/studio/components/interfaces/Storage/StorageMenu.tsx @@ -10,7 +10,7 @@ import { useBucketsQuery } from 'data/storage/buckets-query' import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject' import { IS_PLATFORM } from 'lib/constants' import { useStorageExplorerStateSnapshot } from 'state/storage-explorer' -import { Alert_Shadcn_, AlertDescription_Shadcn_, AlertTitle_Shadcn_, Menu } from 'ui' +import { Alert_Shadcn_, AlertDescription_Shadcn_, AlertTitle_Shadcn_, cn, Menu } from 'ui' import { InfoTooltip } from 'ui-patterns/info-tooltip' import { InnerSideBarEmptyPanel, @@ -70,15 +70,12 @@ export const StorageMenu = () => { [sortedBuckets, searchText] ) const tempNotSupported = error?.message.includes('Tenant config') && isBranch + const isVirtualized = buckets.length > 50 return ( <> - -
+ +
@@ -110,8 +107,17 @@ export const StorageMenu = () => {
-
-
+
+
0 + ? 'mb-3' + : 'mb-5' + )} + > All buckets} /> {isLoading && ( @@ -165,27 +171,27 @@ export const StorageMenu = () => { )}
+
-
- Configuration} /> - - -

Policies

+
+ Configuration} /> + + +

Policies

+
+ + {IS_PLATFORM && ( + + +
+

Settings

+ {isListV2UpgradeAvailable && ( + Upgrade available + )} +
- {IS_PLATFORM && ( - - -
-

Settings

- {isListV2UpgradeAvailable && ( - Upgrade available - )} -
-
- - )} -
+ )}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/QuickstartTemplatesWidget.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/QuickstartTemplatesWidget.tsx index e4fb1ee0a31ce..14d2336a7755d 100644 --- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/QuickstartTemplatesWidget.tsx +++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/QuickstartTemplatesWidget.tsx @@ -1,6 +1,7 @@ import { Columns3, Layers, Table2 } from 'lucide-react' import { useCallback, useEffect, useState } from 'react' import { toast } from 'sonner' + import { cn, Tooltip, TooltipContent, TooltipTrigger } from 'ui' import type { TableField } from '../TableEditor.types' import { tableTemplates } from './templates' diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/templates.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/templates.ts index 68dd6dfe4da7a..27e101814b995 100644 --- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/templates.ts +++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/templates.ts @@ -12,12 +12,7 @@ export const tableTemplates: Record = { isPrimary: true, default: 'gen_random_uuid()', }, - { - name: 'user_id', - type: 'uuid', - nullable: false, - unique: true, - }, + { name: 'user_id', type: 'uuid', nullable: false, unique: true }, { name: 'username', type: 'text', nullable: true, unique: true }, { name: 'display_name', type: 'text', nullable: true }, { name: 'avatar_url', type: 'text', nullable: true }, @@ -40,11 +35,7 @@ export const tableTemplates: Record = { isPrimary: true, default: 'gen_random_uuid()', }, - { - name: 'author_id', - type: 'uuid', - nullable: false, - }, + { name: 'author_id', type: 'uuid', nullable: false }, { name: 'content', type: 'text', nullable: false }, { name: 'image_url', type: 'text', nullable: true }, { name: 'likes_count', type: 'int4', nullable: false, default: '0' }, @@ -65,16 +56,8 @@ export const tableTemplates: Record = { isPrimary: true, default: 'gen_random_uuid()', }, - { - name: 'follower_id', - type: 'uuid', - nullable: false, - }, - { - name: 'following_id', - type: 'uuid', - nullable: false, - }, + { name: 'follower_id', type: 'uuid', nullable: false }, + { name: 'following_id', type: 'uuid', nullable: false }, { name: 'created_at', type: 'timestamptz', nullable: false, default: 'now()' }, ], rationale: 'Tracks relationships between followers and followed users', @@ -120,12 +103,8 @@ export const tableTemplates: Record = { default: 'gen_random_uuid()', }, { name: 'order_number', type: 'text', nullable: false, unique: true }, - { - name: 'customer_id', - type: 'uuid', - nullable: false, - }, - { name: 'status', type: 'text', nullable: false, default: "'pending'" }, + { name: 'customer_id', type: 'uuid', nullable: false }, + { name: 'status', type: 'text', nullable: false, default: 'pending' }, { name: 'subtotal', type: 'numeric', nullable: false }, { name: 'tax', type: 'numeric', nullable: false, default: '0' }, { name: 'shipping', type: 'numeric', nullable: false, default: '0' }, @@ -147,16 +126,8 @@ export const tableTemplates: Record = { isPrimary: true, default: 'gen_random_uuid()', }, - { - name: 'user_id', - type: 'uuid', - nullable: false, - }, - { - name: 'product_id', - type: 'uuid', - nullable: false, - }, + { name: 'user_id', type: 'uuid', nullable: false }, + { name: 'product_id', type: 'uuid', nullable: false }, { name: 'quantity', type: 'int4', nullable: false, default: '1' }, { name: 'added_at', type: 'timestamptz', nullable: false, default: 'now()' }, ], @@ -180,11 +151,7 @@ export const tableTemplates: Record = { { name: 'content', type: 'text', nullable: true }, { name: 'excerpt', type: 'text', nullable: true }, { name: 'cover_image', type: 'text', nullable: true }, - { - name: 'author_id', - type: 'uuid', - nullable: false, - }, + { name: 'author_id', type: 'uuid', nullable: false }, { name: 'status', type: 'text', nullable: false, default: "'draft'" }, { name: 'published_at', type: 'timestamptz', nullable: true }, { name: 'created_at', type: 'timestamptz', nullable: false, default: 'now()' }, @@ -222,11 +189,7 @@ export const tableTemplates: Record = { isPrimary: true, default: 'gen_random_uuid()', }, - { - name: 'article_id', - type: 'uuid', - nullable: false, - }, + { name: 'article_id', type: 'uuid', nullable: false }, { name: 'author_name', type: 'text', nullable: false }, { name: 'author_email', type: 'text', nullable: false }, { name: 'content', type: 'text', nullable: false }, @@ -251,13 +214,9 @@ export const tableTemplates: Record = { { name: 'title', type: 'text', nullable: false }, { name: 'description', type: 'text', nullable: true }, { name: 'completed', type: 'bool', nullable: false, default: 'false' }, - { name: 'priority', type: 'text', nullable: true, default: "'medium'" }, + { name: 'priority', type: 'text', nullable: true, default: 'medium' }, { name: 'due_date', type: 'date', nullable: true }, - { - name: 'user_id', - type: 'uuid', - nullable: false, - }, + { name: 'user_id', type: 'uuid', nullable: false }, { name: 'list_id', type: 'uuid', nullable: true }, { name: 'created_at', type: 'timestamptz', nullable: false, default: 'now()' }, { name: 'updated_at', type: 'timestamptz', nullable: false, default: 'now()' }, @@ -279,11 +238,7 @@ export const tableTemplates: Record = { { name: 'description', type: 'text', nullable: true }, { name: 'color', type: 'text', nullable: true }, { name: 'icon', type: 'text', nullable: true }, - { - name: 'user_id', - type: 'uuid', - nullable: false, - }, + { name: 'user_id', type: 'uuid', nullable: false }, { name: 'created_at', type: 'timestamptz', nullable: false, default: 'now()' }, { name: 'updated_at', type: 'timestamptz', nullable: false, default: 'now()' }, ], @@ -300,11 +255,7 @@ export const tableTemplates: Record = { isPrimary: true, default: 'gen_random_uuid()', }, - { - name: 'task_id', - type: 'uuid', - nullable: false, - }, + { name: 'task_id', type: 'uuid', nullable: false }, { name: 'title', type: 'text', nullable: false }, { name: 'completed', type: 'bool', nullable: false, default: 'false' }, { name: 'position', type: 'int4', nullable: false, default: '0' }, @@ -325,11 +276,7 @@ export const tableTemplates: Record = { isPrimary: true, default: 'gen_random_uuid()', }, - { - name: 'user_id', - type: 'uuid', - nullable: true, - }, + { name: 'user_id', type: 'uuid', nullable: true }, { name: 'session_id', type: 'text', nullable: true }, { name: 'event_type', type: 'text', nullable: false }, { name: 'properties', type: 'jsonb', nullable: true }, @@ -350,11 +297,7 @@ export const tableTemplates: Record = { isPrimary: true, default: 'gen_random_uuid()', }, - { - name: 'user_id', - type: 'uuid', - nullable: true, - }, + { name: 'user_id', type: 'uuid', nullable: true }, { name: 'session_id', type: 'text', nullable: true }, { name: 'path', type: 'text', nullable: false }, { name: 'referrer', type: 'text', nullable: true }, diff --git a/apps/studio/components/layouts/AuthLayout/AuthEmailsLayout.tsx b/apps/studio/components/layouts/AuthLayout/AuthEmailsLayout.tsx index fe69585fe33a0..1d2754ffc5c4a 100644 --- a/apps/studio/components/layouts/AuthLayout/AuthEmailsLayout.tsx +++ b/apps/studio/components/layouts/AuthLayout/AuthEmailsLayout.tsx @@ -8,6 +8,7 @@ import AuthLayout from './AuthLayout' export const AuthEmailsLayout = ({ children }: PropsWithChildren<{}>) => { const { ref } = useParams() + const showEmails = useIsFeatureEnabled('authentication:emails') const navItems = [ diff --git a/apps/studio/components/layouts/Tabs/NewTab.tsx b/apps/studio/components/layouts/Tabs/NewTab.tsx index 1eb98dc29ebf6..99dbe052b96db 100644 --- a/apps/studio/components/layouts/Tabs/NewTab.tsx +++ b/apps/studio/components/layouts/Tabs/NewTab.tsx @@ -20,7 +20,7 @@ import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject' import { usePHFlag } from 'hooks/ui/useFlag' import { uuidv4 } from 'lib/helpers' import { useProfile } from 'lib/profile' -import { useAiAssistantStateSnapshot, AssistantMessageType } from 'state/ai-assistant-state' +import { AssistantMessageType, useAiAssistantStateSnapshot } from 'state/ai-assistant-state' import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2' import { useTableEditorStateSnapshot } from 'state/table-editor' import { createTabId, useTabsStateSnapshot } from 'state/tabs' diff --git a/apps/studio/components/ui/DisabledWarningDueToIncident.tsx b/apps/studio/components/ui/DisabledWarningDueToIncident.tsx deleted file mode 100644 index fc337e4a80ad3..0000000000000 --- a/apps/studio/components/ui/DisabledWarningDueToIncident.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import InformationBox from 'components/ui/InformationBox' -import { AlertCircle } from 'lucide-react' - -interface DisabledWarningDueToIncidentProps { - title: string -} - -const DisabledWarningDueToIncident = ({ title }: DisabledWarningDueToIncidentProps) => { - return ( - } - defaultVisibility={true} - hideCollapse - title={title} - description={ -
-

- Our engineers are currently working on a fix. You can follow updates on{' '} - - https://status.supabase.com/ - -

-
- } - /> - ) -} - -export default DisabledWarningDueToIncident diff --git a/apps/studio/data/__templates/resource-query.ts b/apps/studio/data/__templates/resource-query.ts index 0f0b0501376e9..2aff5ed875cda 100644 --- a/apps/studio/data/__templates/resource-query.ts +++ b/apps/studio/data/__templates/resource-query.ts @@ -33,14 +33,12 @@ export const useResourceQuery = ( { projectRef, id }: ResourceVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - resourceKeys.resource(projectRef, id), - ({ signal }) => getResource({ projectRef, id }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: resourceKeys.resource(projectRef, id), + queryFn: ({ signal }) => getResource({ projectRef, id }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined', + ...options, + }) /** * useResourcePrefetch is used for prefetching data. For example, starting a query loading before a page is navigated to. diff --git a/apps/studio/data/__templates/resource-update-mutation.ts b/apps/studio/data/__templates/resource-update-mutation.ts index 0b8f26ff9976d..ef292042c981b 100644 --- a/apps/studio/data/__templates/resource-update-mutation.ts +++ b/apps/studio/data/__templates/resource-update-mutation.ts @@ -34,27 +34,25 @@ export const useResourceUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateResource(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, id } = variables - - await Promise.all([ - queryClient.invalidateQueries(resourceKeys.list(projectRef)), - queryClient.invalidateQueries(resourceKeys.resource(projectRef, id)), - ]) - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to mutate: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateResource(vars), + async onSuccess(data, variables, context) { + const { projectRef, id } = variables + + await Promise.all([ + queryClient.invalidateQueries(resourceKeys.list(projectRef)), + queryClient.invalidateQueries(resourceKeys.resource(projectRef, id)), + ]) + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to mutate: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/__templates/resources-query.ts b/apps/studio/data/__templates/resources-query.ts index 9d15bd55ee77c..8e278b130184f 100644 --- a/apps/studio/data/__templates/resources-query.ts +++ b/apps/studio/data/__templates/resources-query.ts @@ -28,11 +28,12 @@ export const useResourcesQuery = ( { projectRef }: ResourcesVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - resourceKeys.list(projectRef), - ({ signal }) => getResources({ projectRef }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: resourceKeys.list(projectRef), + queryFn: ({ signal }) => getResources({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) /** * useResourcesPrefetch is used for prefetching data. For example, starting a query loading before a page is navigated to. diff --git a/apps/studio/data/access-tokens/access-tokens-create-mutation.ts b/apps/studio/data/access-tokens/access-tokens-create-mutation.ts index c4f2d182383ac..6a0990ebf4a88 100644 --- a/apps/studio/data/access-tokens/access-tokens-create-mutation.ts +++ b/apps/studio/data/access-tokens/access-tokens-create-mutation.ts @@ -32,22 +32,20 @@ export const useAccessTokenCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createAccessToken(vars), - { - async onSuccess(data, variables, context) { - await queryClient.invalidateQueries(accessTokenKeys.list()) - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create access token: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createAccessToken(vars), + async onSuccess(data, variables, context) { + await queryClient.invalidateQueries(accessTokenKeys.list()) + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create access token: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/access-tokens/access-tokens-delete-mutation.ts b/apps/studio/data/access-tokens/access-tokens-delete-mutation.ts index 8d536cd81a8f5..b4169903648f7 100644 --- a/apps/studio/data/access-tokens/access-tokens-delete-mutation.ts +++ b/apps/studio/data/access-tokens/access-tokens-delete-mutation.ts @@ -30,22 +30,20 @@ export const useAccessTokenDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteAccessToken(vars), - { - async onSuccess(data, variables, context) { - await queryClient.invalidateQueries(accessTokenKeys.list()) - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete access token: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteAccessToken(vars), + async onSuccess(data, variables, context) { + await queryClient.invalidateQueries(accessTokenKeys.list()) + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete access token: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/access-tokens/access-tokens-query.ts b/apps/studio/data/access-tokens/access-tokens-query.ts index 44deafedbbfae..7e882a7a170cd 100644 --- a/apps/studio/data/access-tokens/access-tokens-query.ts +++ b/apps/studio/data/access-tokens/access-tokens-query.ts @@ -21,8 +21,8 @@ export const useAccessTokensQuery = ({ enabled = true, ...options }: UseQueryOptions = {}) => - useQuery( - accessTokenKeys.list(), - ({ signal }) => getAccessTokens(signal), - options - ) + useQuery({ + queryKey: accessTokenKeys.list(), + queryFn: ({ signal }) => getAccessTokens(signal), + ...options, + }) diff --git a/apps/studio/data/actions/action-detail-query.ts b/apps/studio/data/actions/action-detail-query.ts index 4e34849c78faa..b2957ef8e5fd3 100644 --- a/apps/studio/data/actions/action-detail-query.ts +++ b/apps/studio/data/actions/action-detail-query.ts @@ -23,8 +23,10 @@ export const useActionRunQuery = ( { ref, run_id }: ActionRunVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - actionKeys.detail(ref, run_id), - ({ signal }) => getActionRun({ ref, run_id }, signal), - { enabled: enabled && Boolean(ref) && Boolean(run_id), staleTime: 0, ...options } - ) + useQuery({ + queryKey: actionKeys.detail(ref, run_id), + queryFn: ({ signal }) => getActionRun({ ref, run_id }, signal), + enabled: enabled && Boolean(ref) && Boolean(run_id), + staleTime: 0, + ...options, + }) diff --git a/apps/studio/data/actions/action-logs-query.ts b/apps/studio/data/actions/action-logs-query.ts index 218eed45a7293..27270834def79 100644 --- a/apps/studio/data/actions/action-logs-query.ts +++ b/apps/studio/data/actions/action-logs-query.ts @@ -29,8 +29,10 @@ export const useActionRunLogsQuery = ( { ref, run_id }: ActionLogsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - actionKeys.detail(ref, run_id), - ({ signal }) => getActionRunLogs({ ref, run_id }, signal), - { enabled: enabled && Boolean(ref) && Boolean(run_id), staleTime: 0, ...options } - ) + useQuery({ + queryKey: actionKeys.detail(ref, run_id), + queryFn: ({ signal }) => getActionRunLogs({ ref, run_id }, signal), + enabled: enabled && Boolean(ref) && Boolean(run_id), + staleTime: 0, + ...options, + }) diff --git a/apps/studio/data/actions/action-runs-query.ts b/apps/studio/data/actions/action-runs-query.ts index d987fd3494d63..64bf56e2a2e06 100644 --- a/apps/studio/data/actions/action-runs-query.ts +++ b/apps/studio/data/actions/action-runs-query.ts @@ -27,8 +27,10 @@ export const useActionsQuery = ( { ref }: ActionsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - actionKeys.list(ref), - ({ signal }) => listActionRuns({ ref }, signal), - { enabled: enabled && Boolean(ref), staleTime: 0, ...options } - ) + useQuery({ + queryKey: actionKeys.list(ref), + queryFn: ({ signal }) => listActionRuns({ ref }, signal), + enabled: enabled && Boolean(ref), + staleTime: 0, + ...options, + }) diff --git a/apps/studio/data/ai/check-api-key-query.ts b/apps/studio/data/ai/check-api-key-query.ts index 01c78a9af6ade..f0c9c61b58d0e 100644 --- a/apps/studio/data/ai/check-api-key-query.ts +++ b/apps/studio/data/ai/check-api-key-query.ts @@ -34,8 +34,9 @@ export const useCheckOpenAIKeyQuery = ({ enabled = true, ...options }: UseQueryOptions = {}) => - useQuery( - aiKeys.apiKey(), - ({ signal }) => checkOpenAIKey(signal), - { enabled: !IS_PLATFORM && enabled, ...options } - ) + useQuery({ + queryKey: aiKeys.apiKey(), + queryFn: ({ signal }) => checkOpenAIKey(signal), + enabled: !IS_PLATFORM && enabled, + ...options, + }) diff --git a/apps/studio/data/ai/rate-message-mutation.ts b/apps/studio/data/ai/rate-message-mutation.ts index 923943e6cfe99..8f9907723cff9 100644 --- a/apps/studio/data/ai/rate-message-mutation.ts +++ b/apps/studio/data/ai/rate-message-mutation.ts @@ -55,20 +55,18 @@ export const useRateMessageMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => rateMessage(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - console.error(`Failed to rate message: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => rateMessage(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + console.error(`Failed to rate message: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/ai/sql-cron-mutation.ts b/apps/studio/data/ai/sql-cron-mutation.ts index 057dfe826aba2..c9c636b056898 100644 --- a/apps/studio/data/ai/sql-cron-mutation.ts +++ b/apps/studio/data/ai/sql-cron-mutation.ts @@ -44,20 +44,18 @@ export const useSqlCronGenerateMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => generateSqlCron(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to generate cron expression: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => generateSqlCron(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to generate cron expression: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/ai/sql-title-mutation.ts b/apps/studio/data/ai/sql-title-mutation.ts index 45147665d9413..a5bf4c95044b0 100644 --- a/apps/studio/data/ai/sql-title-mutation.ts +++ b/apps/studio/data/ai/sql-title-mutation.ts @@ -48,20 +48,18 @@ export const useSqlTitleGenerateMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => generateSqlTitle(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to generate title: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => generateSqlTitle(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to generate title: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/analytics/functions-combined-stats-query.ts b/apps/studio/data/analytics/functions-combined-stats-query.ts index edb4c095162a3..c9fa6f3810356 100644 --- a/apps/studio/data/analytics/functions-combined-stats-query.ts +++ b/apps/studio/data/analytics/functions-combined-stats-query.ts @@ -56,15 +56,14 @@ export const useFunctionsCombinedStatsQuery = = {} ) => - useQuery( - analyticsKeys.functionsCombinedStats(projectRef, { functionId, interval }), - ({ signal }) => getFunctionsCombinedStats({ projectRef, functionId, interval }, signal), - { - enabled: - enabled && - typeof projectRef !== 'undefined' && - typeof functionId !== 'undefined' && - typeof interval !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: analyticsKeys.functionsCombinedStats(projectRef, { functionId, interval }), + queryFn: ({ signal }) => + getFunctionsCombinedStats({ projectRef, functionId, interval }, signal), + enabled: + enabled && + typeof projectRef !== 'undefined' && + typeof functionId !== 'undefined' && + typeof interval !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/analytics/functions-req-stats-query.ts b/apps/studio/data/analytics/functions-req-stats-query.ts index 5a765b4148f43..0b974c4b12d24 100644 --- a/apps/studio/data/analytics/functions-req-stats-query.ts +++ b/apps/studio/data/analytics/functions-req-stats-query.ts @@ -56,15 +56,13 @@ export const useFunctionsReqStatsQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - analyticsKeys.functionsReqStats(projectRef, { functionId, interval }), - ({ signal }) => getFunctionsReqStats({ projectRef, functionId, interval }, signal), - { - enabled: - enabled && - typeof projectRef !== 'undefined' && - typeof functionId !== 'undefined' && - typeof interval !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: analyticsKeys.functionsReqStats(projectRef, { functionId, interval }), + queryFn: ({ signal }) => getFunctionsReqStats({ projectRef, functionId, interval }, signal), + enabled: + enabled && + typeof projectRef !== 'undefined' && + typeof functionId !== 'undefined' && + typeof interval !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/analytics/functions-resource-usage-query.ts b/apps/studio/data/analytics/functions-resource-usage-query.ts index ae767d52ebbd0..45d8d1a4f81d3 100644 --- a/apps/studio/data/analytics/functions-resource-usage-query.ts +++ b/apps/studio/data/analytics/functions-resource-usage-query.ts @@ -56,15 +56,14 @@ export const useFunctionsResourceUsageQuery = = {} ) => - useQuery( - analyticsKeys.functionsResourceUsage(projectRef, { functionId, interval }), - ({ signal }) => getFunctionsResourceUsage({ projectRef, functionId, interval }, signal), - { - enabled: - enabled && - typeof projectRef !== 'undefined' && - typeof functionId !== 'undefined' && - typeof interval !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: analyticsKeys.functionsResourceUsage(projectRef, { functionId, interval }), + queryFn: ({ signal }) => + getFunctionsResourceUsage({ projectRef, functionId, interval }, signal), + enabled: + enabled && + typeof projectRef !== 'undefined' && + typeof functionId !== 'undefined' && + typeof interval !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/analytics/infra-monitoring-query.ts b/apps/studio/data/analytics/infra-monitoring-query.ts index 00f607522d8a5..e57ecc3a50777 100644 --- a/apps/studio/data/analytics/infra-monitoring-query.ts +++ b/apps/studio/data/analytics/infra-monitoring-query.ts @@ -78,40 +78,38 @@ export const useInfraMonitoringQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - analyticsKeys.infraMonitoring(projectRef, { + useQuery({ + queryKey: analyticsKeys.infraMonitoring(projectRef, { attribute, startDate, endDate, interval, databaseIdentifier, }), - ({ signal }) => + queryFn: ({ signal }) => getInfraMonitoring( { projectRef, attribute, startDate, endDate, interval, databaseIdentifier }, signal ), - { - enabled: - enabled && - typeof projectRef !== 'undefined' && - typeof attribute !== 'undefined' && - typeof startDate !== 'undefined' && - typeof endDate !== 'undefined', - select(data) { - return { - ...data, - data: data.data.map((x) => { - return { - ...x, - [attribute]: - modifier !== undefined ? modifier(Number(x[attribute])) : Number(x[attribute]), - periodStartFormatted: dayjs(x.period_start).format(dateFormat), - } - }), - } as TData - }, - staleTime: 1000 * 60, // default good for a minute - ...options, - } - ) + enabled: + enabled && + typeof projectRef !== 'undefined' && + typeof attribute !== 'undefined' && + typeof startDate !== 'undefined' && + typeof endDate !== 'undefined', + select(data) { + return { + ...data, + data: data.data.map((x) => { + return { + ...x, + [attribute]: + modifier !== undefined ? modifier(Number(x[attribute])) : Number(x[attribute]), + periodStartFormatted: dayjs(x.period_start).format(dateFormat), + } + }), + } as TData + }, + staleTime: 1000 * 60, + ...options, + }) diff --git a/apps/studio/data/analytics/org-daily-stats-query.ts b/apps/studio/data/analytics/org-daily-stats-query.ts index db4fd96f2ac12..ae80bcf4c0682 100644 --- a/apps/studio/data/analytics/org-daily-stats-query.ts +++ b/apps/studio/data/analytics/org-daily-stats-query.ts @@ -151,16 +151,14 @@ export const useOrgDailyStatsQuery = ( { orgSlug, startDate, endDate, projectRef }: OrgDailyStatsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - analyticsKeys.orgDailyStats(orgSlug, { startDate, endDate, projectRef }), - ({ signal }) => getOrgDailyStats({ orgSlug, startDate, endDate, projectRef }, signal), - { - enabled: - enabled && - typeof orgSlug !== 'undefined' && - typeof startDate !== 'undefined' && - typeof endDate !== 'undefined', - staleTime: 1000 * 60 * 60, // default good for an hour for now - ...options, - } - ) + useQuery({ + queryKey: analyticsKeys.orgDailyStats(orgSlug, { startDate, endDate, projectRef }), + queryFn: ({ signal }) => getOrgDailyStats({ orgSlug, startDate, endDate, projectRef }, signal), + enabled: + enabled && + typeof orgSlug !== 'undefined' && + typeof startDate !== 'undefined' && + typeof endDate !== 'undefined', + staleTime: 1000 * 60 * 60, + ...options, + }) diff --git a/apps/studio/data/analytics/project-daily-stats-query.ts b/apps/studio/data/analytics/project-daily-stats-query.ts index f8bda24d30115..610a87397ca2f 100644 --- a/apps/studio/data/analytics/project-daily-stats-query.ts +++ b/apps/studio/data/analytics/project-daily-stats-query.ts @@ -50,21 +50,20 @@ export const useProjectDailyStatsQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - analyticsKeys.infraMonitoring(projectRef, { + useQuery({ + queryKey: analyticsKeys.infraMonitoring(projectRef, { attribute, startDate, endDate, }), - ({ signal }) => getProjectDailyStats({ projectRef, attribute, startDate, endDate }, signal), - { - enabled: - enabled && - typeof projectRef !== 'undefined' && - typeof attribute !== 'undefined' && - typeof startDate !== 'undefined' && - typeof endDate !== 'undefined', - staleTime: 1000 * 60 * 30, // default good for 30m, stats only refresh once a day - ...options, - } - ) + queryFn: ({ signal }) => + getProjectDailyStats({ projectRef, attribute, startDate, endDate }, signal), + enabled: + enabled && + typeof projectRef !== 'undefined' && + typeof attribute !== 'undefined' && + typeof startDate !== 'undefined' && + typeof endDate !== 'undefined', + staleTime: 1000 * 60 * 30, + ...options, + }) diff --git a/apps/studio/data/analytics/project-log-requests-count-query.ts b/apps/studio/data/analytics/project-log-requests-count-query.ts index 0d6e5b5863dbb..8898c8a227a73 100644 --- a/apps/studio/data/analytics/project-log-requests-count-query.ts +++ b/apps/studio/data/analytics/project-log-requests-count-query.ts @@ -40,14 +40,12 @@ export const useProjectLogRequestsCountQuery = = {} ) => - useQuery( - analyticsKeys.usageApiRequestsCount(projectRef), - ({ signal }) => getProjectLogRequestsCountStats({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: analyticsKeys.usageApiRequestsCount(projectRef), + queryFn: ({ signal }) => getProjectLogRequestsCountStats({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) export function prefetchProjectLogRequestsCount( client: QueryClient, diff --git a/apps/studio/data/analytics/project-log-stats-query.ts b/apps/studio/data/analytics/project-log-stats-query.ts index 76167f33d9eec..be3379ef52159 100644 --- a/apps/studio/data/analytics/project-log-stats-query.ts +++ b/apps/studio/data/analytics/project-log-stats-query.ts @@ -60,14 +60,12 @@ export const useProjectLogStatsQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - analyticsKeys.usageApiCounts(projectRef, interval), - ({ signal }) => getProjectLogStats({ projectRef, interval }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof interval !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: analyticsKeys.usageApiCounts(projectRef, interval), + queryFn: ({ signal }) => getProjectLogStats({ projectRef, interval }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && typeof interval !== 'undefined', + ...options, + }) export function prefetchProjectLogStats( client: QueryClient, diff --git a/apps/studio/data/api-authorization/api-authorization-approve-mutation.ts b/apps/studio/data/api-authorization/api-authorization-approve-mutation.ts index 56f52c2eafe1e..832c71149b5e0 100644 --- a/apps/studio/data/api-authorization/api-authorization-approve-mutation.ts +++ b/apps/studio/data/api-authorization/api-authorization-approve-mutation.ts @@ -36,17 +36,15 @@ export const useApiAuthorizationApproveMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => approveApiAuthorization(vars), - { - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to approve authorization request: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => approveApiAuthorization(vars), + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to approve authorization request: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/api-authorization/api-authorization-decline-mutation.ts b/apps/studio/data/api-authorization/api-authorization-decline-mutation.ts index 7976a7d94af55..bf1eec660ec10 100644 --- a/apps/studio/data/api-authorization/api-authorization-decline-mutation.ts +++ b/apps/studio/data/api-authorization/api-authorization-decline-mutation.ts @@ -35,17 +35,15 @@ export const useApiAuthorizationDeclineMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => declineApiAuthorization(vars), - { - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to decline authorization request: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => declineApiAuthorization(vars), + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to decline authorization request: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/api-authorization/api-authorization-query.ts b/apps/studio/data/api-authorization/api-authorization-query.ts index 37d0f58356c04..bfe1f9a7cc6be 100644 --- a/apps/studio/data/api-authorization/api-authorization-query.ts +++ b/apps/studio/data/api-authorization/api-authorization-query.ts @@ -42,11 +42,9 @@ export const useApiAuthorizationQuery = ( { id }: ApiAuthorizationVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - resourceKeys.resource(id), - ({ signal }) => getApiAuthorizationDetails({ id }, signal), - { - enabled: enabled && typeof id !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: resourceKeys.resource(id), + queryFn: ({ signal }) => getApiAuthorizationDetails({ id }, signal), + enabled: enabled && typeof id !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/api-keys/[id]/api-key-id-query.ts b/apps/studio/data/api-keys/[id]/api-key-id-query.ts index 06aae547d139f..87ab4073ae8a8 100644 --- a/apps/studio/data/api-keys/[id]/api-key-id-query.ts +++ b/apps/studio/data/api-keys/[id]/api-key-id-query.ts @@ -37,11 +37,9 @@ export const useAPIKeyIdQuery = ( { projectRef, id, reveal }: APIKeyVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - apiKeysKeys.single(projectRef, id), - ({ signal }) => getAPIKeysById({ projectRef, id, reveal }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: apiKeysKeys.single(projectRef, id), + queryFn: ({ signal }) => getAPIKeysById({ projectRef, id, reveal }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/api-keys/[id]/api-key-id-update-mutation.ts b/apps/studio/data/api-keys/[id]/api-key-id-update-mutation.ts index 18751a12448d3..05cee5366a8c6 100644 --- a/apps/studio/data/api-keys/[id]/api-key-id-update-mutation.ts +++ b/apps/studio/data/api-keys/[id]/api-key-id-update-mutation.ts @@ -47,24 +47,22 @@ export const useResourceUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateAPIKeysById(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, id } = variables + return useMutation({ + mutationFn: (vars) => updateAPIKeysById(vars), + async onSuccess(data, variables, context) { + const { projectRef, id } = variables - await queryClient.invalidateQueries(apiKeysKeys.list(projectRef)) + await queryClient.invalidateQueries(apiKeysKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to mutate: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to mutate: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/api-keys/api-key-create-mutation.ts b/apps/studio/data/api-keys/api-key-create-mutation.ts index f84d56055ec57..b5838231537df 100644 --- a/apps/studio/data/api-keys/api-key-create-mutation.ts +++ b/apps/studio/data/api-keys/api-key-create-mutation.ts @@ -63,24 +63,22 @@ export const useAPIKeyCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createAPIKey(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables + return useMutation({ + mutationFn: (vars) => createAPIKey(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables - await queryClient.invalidateQueries(apiKeysKeys.list(projectRef)) + await queryClient.invalidateQueries(apiKeysKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create API key: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create API key: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/api-keys/api-key-delete-mutation.ts b/apps/studio/data/api-keys/api-key-delete-mutation.ts index 0625eab78d086..d85ab96687f0c 100644 --- a/apps/studio/data/api-keys/api-key-delete-mutation.ts +++ b/apps/studio/data/api-keys/api-key-delete-mutation.ts @@ -35,24 +35,22 @@ export const useAPIKeyDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteAPIKey(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - - await queryClient.invalidateQueries(apiKeysKeys.list(projectRef)) - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete API key: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteAPIKey(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + + await queryClient.invalidateQueries(apiKeysKeys.list(projectRef)) + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete API key: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/api-keys/api-keys-query.ts b/apps/studio/data/api-keys/api-keys-query.ts index 5b746e88be730..596ae00710bfa 100644 --- a/apps/studio/data/api-keys/api-keys-query.ts +++ b/apps/studio/data/api-keys/api-keys-query.ts @@ -70,14 +70,12 @@ export const useAPIKeysQuery = ( { projectRef, reveal = false }: APIKeysVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => { - return useQuery( - apiKeysKeys.list(projectRef, reveal), - ({ signal }) => getAPIKeys({ projectRef, reveal }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + return useQuery({ + queryKey: apiKeysKeys.list(projectRef, reveal), + queryFn: ({ signal }) => getAPIKeys({ projectRef, reveal }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) } export const getKeys = (apiKeys: APIKey[] = []) => { diff --git a/apps/studio/data/api-keys/legacy-api-key-toggle-mutation.ts b/apps/studio/data/api-keys/legacy-api-key-toggle-mutation.ts index 0f0a07c43e37b..fc2a370a6063e 100644 --- a/apps/studio/data/api-keys/legacy-api-key-toggle-mutation.ts +++ b/apps/studio/data/api-keys/legacy-api-key-toggle-mutation.ts @@ -35,26 +35,24 @@ export const useToggleLegacyAPIKeysMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => toggleLegacyAPIKeys(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - - await queryClient.invalidateQueries(apiKeysKeys.status(projectRef)) - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error( - `Failed to ${variables.enabled ? 're-enable' : 'disable'} JWT-based API keys: ${data.message}` - ) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => toggleLegacyAPIKeys(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + + await queryClient.invalidateQueries(apiKeysKeys.status(projectRef)) + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error( + `Failed to ${variables.enabled ? 're-enable' : 'disable'} JWT-based API keys: ${data.message}` + ) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/api-keys/legacy-api-keys-status-query.ts b/apps/studio/data/api-keys/legacy-api-keys-status-query.ts index 73f509780f126..9d314ea54074f 100644 --- a/apps/studio/data/api-keys/legacy-api-keys-status-query.ts +++ b/apps/studio/data/api-keys/legacy-api-keys-status-query.ts @@ -33,11 +33,9 @@ export const useLegacyAPIKeysStatusQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - apiKeysKeys.status(projectRef), - ({ signal }) => getLegacyAPIKeysStatus({ projectRef }, signal), - { - enabled: IS_PLATFORM && enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: apiKeysKeys.status(projectRef), + queryFn: ({ signal }) => getLegacyAPIKeysStatus({ projectRef }, signal), + enabled: IS_PLATFORM && enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/api-settings/create-and-expose-api-schema-mutation.ts b/apps/studio/data/api-settings/create-and-expose-api-schema-mutation.ts index c3f2f2c0b5365..60946310a3489 100644 --- a/apps/studio/data/api-settings/create-and-expose-api-schema-mutation.ts +++ b/apps/studio/data/api-settings/create-and-expose-api-schema-mutation.ts @@ -65,7 +65,8 @@ export const useCreateAndExposeAPISchemaMutation = ({ CreateAndExposeAPISchemaData, ResponseError, CreateAndExposeAPISchemaVariables - >((vars) => createAndExposeApiSchema(vars), { + >({ + mutationFn: (vars) => createAndExposeApiSchema(vars), async onSuccess(data, variables, context) { const { projectRef } = variables await Promise.all([ diff --git a/apps/studio/data/auth/auth-config-query.ts b/apps/studio/data/auth/auth-config-query.ts index 337b30f4bac04..9d84e0634dfc1 100644 --- a/apps/studio/data/auth/auth-config-query.ts +++ b/apps/studio/data/auth/auth-config-query.ts @@ -37,14 +37,12 @@ export const useAuthConfigQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - authKeys.authConfig(projectRef), - ({ signal }) => getProjectAuthConfig({ projectRef }, signal), - { - enabled: enabled && IS_PLATFORM && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: authKeys.authConfig(projectRef), + queryFn: ({ signal }) => getProjectAuthConfig({ projectRef }, signal), + enabled: enabled && IS_PLATFORM && typeof projectRef !== 'undefined', + ...options, + }) export const useAuthConfigPrefetch = ({ projectRef }: AuthConfigVariables) => { const client = useQueryClient() diff --git a/apps/studio/data/auth/auth-config-update-mutation.ts b/apps/studio/data/auth/auth-config-update-mutation.ts index 6d4e15979833c..019bfe1699a39 100644 --- a/apps/studio/data/auth/auth-config-update-mutation.ts +++ b/apps/studio/data/auth/auth-config-update-mutation.ts @@ -37,22 +37,20 @@ export const useAuthConfigUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateAuthConfig(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(authKeys.authConfig(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update auth configuration: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateAuthConfig(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(authKeys.authConfig(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update auth configuration: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/auth/auth-hooks-update-mutation.ts b/apps/studio/data/auth/auth-hooks-update-mutation.ts index 8b8ebecffe645..535901a9615ec 100644 --- a/apps/studio/data/auth/auth-hooks-update-mutation.ts +++ b/apps/studio/data/auth/auth-hooks-update-mutation.ts @@ -33,22 +33,20 @@ export const useAuthHooksUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateAuthHooks(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(authKeys.authConfig(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update auth hooks: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateAuthHooks(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(authKeys.authConfig(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update auth hooks: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/auth/session-access-token-query.ts b/apps/studio/data/auth/session-access-token-query.ts index 095a57d48fa16..c5f042e128846 100644 --- a/apps/studio/data/auth/session-access-token-query.ts +++ b/apps/studio/data/auth/session-access-token-query.ts @@ -22,8 +22,8 @@ export const useSessionAccessTokenQuery = ({ enabled = true, ...options }: UseQueryOptions = {}) => - useQuery( - authKeys.accessToken(), - () => getSessionAccessToken(), - options - ) + useQuery({ + queryKey: authKeys.accessToken(), + queryFn: () => getSessionAccessToken(), + ...options, + }) diff --git a/apps/studio/data/auth/user-create-mutation.ts b/apps/studio/data/auth/user-create-mutation.ts index 533c8e2df418b..1db52c575a9c6 100644 --- a/apps/studio/data/auth/user-create-mutation.ts +++ b/apps/studio/data/auth/user-create-mutation.ts @@ -39,24 +39,22 @@ export const useUserCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createUser(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - - await Promise.all([queryClient.invalidateQueries(authKeys.usersInfinite(projectRef))]) - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create user: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createUser(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + + await Promise.all([queryClient.invalidateQueries(authKeys.usersInfinite(projectRef))]) + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create user: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/auth/user-delete-mfa-factors-mutation.ts b/apps/studio/data/auth/user-delete-mfa-factors-mutation.ts index 149952ad71a9c..7ae5937528b43 100644 --- a/apps/studio/data/auth/user-delete-mfa-factors-mutation.ts +++ b/apps/studio/data/auth/user-delete-mfa-factors-mutation.ts @@ -29,21 +29,19 @@ export const useUserDeleteMFAFactorsMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => deleteMFAFactors(vars), - { - async onSuccess(data, variables, context) { - // [Joshen] If we need to invalidate any queries - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete the user's MFA factors: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteMFAFactors(vars), + async onSuccess(data, variables, context) { + // [Joshen] If we need to invalidate any queries + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete the user's MFA factors: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/auth/user-delete-mutation.ts b/apps/studio/data/auth/user-delete-mutation.ts index 0b67188f05238..62e0c671fc27d 100644 --- a/apps/studio/data/auth/user-delete-mutation.ts +++ b/apps/studio/data/auth/user-delete-mutation.ts @@ -31,26 +31,24 @@ export const useUserDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteUser(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, skipInvalidation = false } = variables - - if (!skipInvalidation) { - await Promise.all([queryClient.invalidateQueries(authKeys.usersInfinite(projectRef))]) - } - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete user: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteUser(vars), + async onSuccess(data, variables, context) { + const { projectRef, skipInvalidation = false } = variables + + if (!skipInvalidation) { + await Promise.all([queryClient.invalidateQueries(authKeys.usersInfinite(projectRef))]) + } + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete user: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/auth/user-invite-mutation.ts b/apps/studio/data/auth/user-invite-mutation.ts index 42bff571c6d76..77fcfd13e3116 100644 --- a/apps/studio/data/auth/user-invite-mutation.ts +++ b/apps/studio/data/auth/user-invite-mutation.ts @@ -31,24 +31,22 @@ export const useUserInviteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => inviteUser(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - - await Promise.all([queryClient.invalidateQueries(authKeys.usersInfinite(projectRef))]) - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to invite user: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => inviteUser(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + + await Promise.all([queryClient.invalidateQueries(authKeys.usersInfinite(projectRef))]) + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to invite user: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/auth/user-reset-password-mutation.ts b/apps/studio/data/auth/user-reset-password-mutation.ts index aeaef00b5d8b6..d39a5a9a692e0 100644 --- a/apps/studio/data/auth/user-reset-password-mutation.ts +++ b/apps/studio/data/auth/user-reset-password-mutation.ts @@ -31,21 +31,19 @@ export const useUserResetPasswordMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => resetPassword(vars), - { - async onSuccess(data, variables, context) { - // [Joshen] If we need to invalidate any queries - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to reset user password: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => resetPassword(vars), + async onSuccess(data, variables, context) { + // [Joshen] If we need to invalidate any queries + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to reset user password: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/auth/user-send-magic-link-mutation.ts b/apps/studio/data/auth/user-send-magic-link-mutation.ts index 22037ab8938fc..127fb33a313c9 100644 --- a/apps/studio/data/auth/user-send-magic-link-mutation.ts +++ b/apps/studio/data/auth/user-send-magic-link-mutation.ts @@ -31,21 +31,19 @@ export const useUserSendMagicLinkMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => sendMagicLink(vars), - { - async onSuccess(data, variables, context) { - // [Joshen] If we need to invalidate any queries - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to send magic link: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => sendMagicLink(vars), + async onSuccess(data, variables, context) { + // [Joshen] If we need to invalidate any queries + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to send magic link: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/auth/user-send-otp-mutation.ts b/apps/studio/data/auth/user-send-otp-mutation.ts index 1ba5d3239fe6e..6072fcb969c22 100644 --- a/apps/studio/data/auth/user-send-otp-mutation.ts +++ b/apps/studio/data/auth/user-send-otp-mutation.ts @@ -31,21 +31,19 @@ export const useUserSendOTPMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => sendOTP(vars), - { - async onSuccess(data, variables, context) { - // [Joshen] If we need to invalidate any queries - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to send magic link: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => sendOTP(vars), + async onSuccess(data, variables, context) { + // [Joshen] If we need to invalidate any queries + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to send magic link: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/auth/user-update-mutation.ts b/apps/studio/data/auth/user-update-mutation.ts index 19cf3ae3b9f67..01209b201256c 100644 --- a/apps/studio/data/auth/user-update-mutation.ts +++ b/apps/studio/data/auth/user-update-mutation.ts @@ -34,22 +34,20 @@ export const useUserUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateUser(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(authKeys.usersInfinite(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update user: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateUser(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(authKeys.usersInfinite(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update user: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/auth/users-count-query.ts b/apps/studio/data/auth/users-count-query.ts index 9c8730eff1013..67052362022e3 100644 --- a/apps/studio/data/auth/users-count-query.ts +++ b/apps/studio/data/auth/users-count-query.ts @@ -65,14 +65,14 @@ export const useUsersCountQuery = ( }: UsersCountVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - authKeys.usersCount(projectRef, { + useQuery({ + queryKey: authKeys.usersCount(projectRef, { keywords, filter, providers, forceExactCount, }), - ({ signal }) => + queryFn: ({ signal }) => getUsersCount( { projectRef, @@ -84,8 +84,6 @@ export const useUsersCountQuery = ( }, signal ), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/auth/validate-spam-mutation.ts b/apps/studio/data/auth/validate-spam-mutation.ts index 78a46ac777d13..920a025f7d735 100644 --- a/apps/studio/data/auth/validate-spam-mutation.ts +++ b/apps/studio/data/auth/validate-spam-mutation.ts @@ -32,20 +32,18 @@ export const useValidateSpamMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => validateSpam(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to validate template: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => validateSpam(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to validate template: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/banned-ips/banned-ips-delete-mutations.ts b/apps/studio/data/banned-ips/banned-ips-delete-mutations.ts index dc0a462fc9994..3fff21f34bafa 100644 --- a/apps/studio/data/banned-ips/banned-ips-delete-mutations.ts +++ b/apps/studio/data/banned-ips/banned-ips-delete-mutations.ts @@ -31,24 +31,22 @@ export const useBannedIPsDeleteMutation = ({ ...options }: Omit, 'mutationFn'> = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteBannedIPs(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - - await queryClient.invalidateQueries(BannedIPKeys.list(projectRef)) - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to unban ips: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteBannedIPs(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + + await queryClient.invalidateQueries(BannedIPKeys.list(projectRef)) + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to unban ips: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/banned-ips/banned-ips-query.ts b/apps/studio/data/banned-ips/banned-ips-query.ts index 89964f6047774..710b68c3fb03b 100644 --- a/apps/studio/data/banned-ips/banned-ips-query.ts +++ b/apps/studio/data/banned-ips/banned-ips-query.ts @@ -30,11 +30,9 @@ export const useBannedIPsQuery = ( { projectRef }: BannedIPVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - BannedIPKeys.list(projectRef), - ({ signal }) => getBannedIPs({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: BannedIPKeys.list(projectRef), + queryFn: ({ signal }) => getBannedIPs({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/branches/branch-create-mutation.ts b/apps/studio/data/branches/branch-create-mutation.ts index 2b338ea056077..08d426c1f20af 100644 --- a/apps/studio/data/branches/branch-create-mutation.ts +++ b/apps/studio/data/branches/branch-create-mutation.ts @@ -52,22 +52,20 @@ export const useBranchCreateMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createBranch(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(branchKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create branch: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createBranch(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(branchKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create branch: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/branches/branch-delete-mutation.ts b/apps/studio/data/branches/branch-delete-mutation.ts index fe0adb6d8d38e..1b9ca55e56e86 100644 --- a/apps/studio/data/branches/branch-delete-mutation.ts +++ b/apps/studio/data/branches/branch-delete-mutation.ts @@ -31,33 +31,31 @@ export const useBranchDeleteMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteBranch(vars), - { - async onSuccess(data, variables, context) { - const { branchRef, projectRef } = variables - setTimeout(() => { - queryClient.invalidateQueries(branchKeys.list(projectRef)) - }, 5000) - - const branches: BranchesData | undefined = queryClient.getQueryData( - branchKeys.list(projectRef) - ) - if (branches) { - const updatedBranches = branches.filter((branch) => branch.project_ref !== branchRef) - queryClient.setQueryData(branchKeys.list(projectRef), updatedBranches) - } - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete branch: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteBranch(vars), + async onSuccess(data, variables, context) { + const { branchRef, projectRef } = variables + setTimeout(() => { + queryClient.invalidateQueries(branchKeys.list(projectRef)) + }, 5000) + + const branches: BranchesData | undefined = queryClient.getQueryData( + branchKeys.list(projectRef) + ) + if (branches) { + const updatedBranches = branches.filter((branch) => branch.project_ref !== branchRef) + queryClient.setQueryData(branchKeys.list(projectRef), updatedBranches) + } + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete branch: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/branches/branch-diff-query.ts b/apps/studio/data/branches/branch-diff-query.ts index bdc83572fee3e..a3976d63a6590 100644 --- a/apps/studio/data/branches/branch-diff-query.ts +++ b/apps/studio/data/branches/branch-diff-query.ts @@ -47,11 +47,9 @@ export const useBranchDiffQuery = ( ...options }: Omit, 'queryKey' | 'queryFn'> = {} ) => - useQuery( - branchKeys.diff(projectRef, branchRef), - () => getBranchDiff({ branchRef, includedSchemas }), - { - enabled: IS_PLATFORM && enabled && Boolean(branchRef), - ...options, - } - ) + useQuery({ + queryKey: branchKeys.diff(projectRef, branchRef), + queryFn: () => getBranchDiff({ branchRef, includedSchemas }), + enabled: IS_PLATFORM && enabled && Boolean(branchRef), + ...options, + }) diff --git a/apps/studio/data/branches/branch-merge-mutation.ts b/apps/studio/data/branches/branch-merge-mutation.ts index b6a1fd5691819..9c2c8bf24d70f 100644 --- a/apps/studio/data/branches/branch-merge-mutation.ts +++ b/apps/studio/data/branches/branch-merge-mutation.ts @@ -63,24 +63,22 @@ export const useBranchMergeMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => mergeBranch(vars), - { - async onSuccess(data, variables, context) { - const { baseProjectRef } = variables - await queryClient.invalidateQueries(branchKeys.list(baseProjectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - let errorMessage = data.message || 'Unknown error occurred' + return useMutation({ + mutationFn: (vars) => mergeBranch(vars), + async onSuccess(data, variables, context) { + const { baseProjectRef } = variables + await queryClient.invalidateQueries(branchKeys.list(baseProjectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + let errorMessage = data.message || 'Unknown error occurred' - toast.error(`Failed to merge branch: ${errorMessage}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + toast.error(`Failed to merge branch: ${errorMessage}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/branches/branch-push-mutation.ts b/apps/studio/data/branches/branch-push-mutation.ts index 1ffb4ac909a80..3b36d83ff0a6e 100644 --- a/apps/studio/data/branches/branch-push-mutation.ts +++ b/apps/studio/data/branches/branch-push-mutation.ts @@ -31,22 +31,20 @@ export const useBranchPushMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => pushBranch(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(branchKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to push branch: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => pushBranch(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(branchKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to push branch: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/branches/branch-query.ts b/apps/studio/data/branches/branch-query.ts index 81fee2ba79bf7..03c83a3e88f60 100644 --- a/apps/studio/data/branches/branch-query.ts +++ b/apps/studio/data/branches/branch-query.ts @@ -29,11 +29,9 @@ export const useBranchQuery = ( { projectRef, branchRef }: BranchVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - branchKeys.detail(projectRef, branchRef), - ({ signal }) => getBranch({ branchRef }, signal), - { - enabled: IS_PLATFORM && enabled && Boolean(branchRef), - ...options, - } - ) + useQuery({ + queryKey: branchKeys.detail(projectRef, branchRef), + queryFn: ({ signal }) => getBranch({ branchRef }, signal), + enabled: IS_PLATFORM && enabled && Boolean(branchRef), + ...options, + }) diff --git a/apps/studio/data/branches/branch-reset-mutation.ts b/apps/studio/data/branches/branch-reset-mutation.ts index f54e61a35c6a5..fd2b21f6a6be8 100644 --- a/apps/studio/data/branches/branch-reset-mutation.ts +++ b/apps/studio/data/branches/branch-reset-mutation.ts @@ -31,22 +31,20 @@ export const useBranchResetMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => resetBranch(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(branchKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to reset branch: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => resetBranch(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(branchKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to reset branch: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/branches/branch-update-mutation.ts b/apps/studio/data/branches/branch-update-mutation.ts index 2ea12830fd08b..f8233395ba9b6 100644 --- a/apps/studio/data/branches/branch-update-mutation.ts +++ b/apps/studio/data/branches/branch-update-mutation.ts @@ -48,22 +48,20 @@ export const useBranchUpdateMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateBranch(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(branchKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update branch: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateBranch(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(branchKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update branch: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/branches/branches-query.ts b/apps/studio/data/branches/branches-query.ts index 69aad2f835a90..cf4f95f4b1720 100644 --- a/apps/studio/data/branches/branches-query.ts +++ b/apps/studio/data/branches/branches-query.ts @@ -38,8 +38,9 @@ export const useBranchesQuery = ( { projectRef }: BranchesVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - branchKeys.list(projectRef), - ({ signal }) => getBranches({ projectRef }, signal), - { enabled: IS_PLATFORM && enabled && Boolean(projectRef), ...options } - ) + useQuery({ + queryKey: branchKeys.list(projectRef), + queryFn: ({ signal }) => getBranches({ projectRef }, signal), + enabled: IS_PLATFORM && enabled && Boolean(projectRef), + ...options, + }) diff --git a/apps/studio/data/config/disk-attributes-query.ts b/apps/studio/data/config/disk-attributes-query.ts index 84c55f721cf6b..eb5f49cb59ef4 100644 --- a/apps/studio/data/config/disk-attributes-query.ts +++ b/apps/studio/data/config/disk-attributes-query.ts @@ -39,11 +39,12 @@ export const useDiskAttributesQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - configKeys.diskAttributes(projectRef), - ({ signal }) => getDiskAttributes({ projectRef }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: configKeys.diskAttributes(projectRef), + queryFn: ({ signal }) => getDiskAttributes({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) export const useRemainingDurationForDiskAttributeUpdate = ({ projectRef, diff --git a/apps/studio/data/config/disk-attributes-update-mutation.ts b/apps/studio/data/config/disk-attributes-update-mutation.ts index 8a289448f3a78..e50d3dbec245a 100644 --- a/apps/studio/data/config/disk-attributes-update-mutation.ts +++ b/apps/studio/data/config/disk-attributes-update-mutation.ts @@ -54,22 +54,20 @@ export const useUpdateDiskAttributesMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateDiskAttributes(vars), - { - async onSuccess(data, variables, context) { - const { ref } = variables - await queryClient.invalidateQueries(configKeys.diskAttributes(ref)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update disk attributes: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateDiskAttributes(vars), + async onSuccess(data, variables, context) { + const { ref } = variables + await queryClient.invalidateQueries(configKeys.diskAttributes(ref)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update disk attributes: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/config/disk-autoscale-config-query.ts b/apps/studio/data/config/disk-autoscale-config-query.ts index bde9263c2fc13..6d44f7f8b0bac 100644 --- a/apps/studio/data/config/disk-autoscale-config-query.ts +++ b/apps/studio/data/config/disk-autoscale-config-query.ts @@ -35,8 +35,9 @@ export const useDiskAutoscaleCustomConfigQuery = = {} ) => - useQuery( - configKeys.diskAutoscaleConfig(projectRef), - ({ signal }) => getDiskAutoscaleCustomConfig({ projectRef }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: configKeys.diskAutoscaleConfig(projectRef), + queryFn: ({ signal }) => getDiskAutoscaleCustomConfig({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/config/disk-autoscale-config-update-mutation.ts b/apps/studio/data/config/disk-autoscale-config-update-mutation.ts index e9c37ceb744ba..6da6272a27942 100644 --- a/apps/studio/data/config/disk-autoscale-config-update-mutation.ts +++ b/apps/studio/data/config/disk-autoscale-config-update-mutation.ts @@ -53,7 +53,8 @@ export const useUpdateDiskAutoscaleConfigMutation = ({ UpdateDiskAutoscaleConfigData, ResponseError, UpdateDiskAutoscaleConfigVariables - >((vars) => updateDiskAutoscaleConfig(vars), { + >({ + mutationFn: (vars) => updateDiskAutoscaleConfig(vars), async onSuccess(data, variables, context) { const { projectRef } = variables await queryClient.invalidateQueries(configKeys.diskAutoscaleConfig(projectRef)) diff --git a/apps/studio/data/config/disk-breakdown-query.ts b/apps/studio/data/config/disk-breakdown-query.ts index 5f5f42c5ce97e..757a289735cca 100644 --- a/apps/studio/data/config/disk-breakdown-query.ts +++ b/apps/studio/data/config/disk-breakdown-query.ts @@ -52,8 +52,9 @@ export const useDiskBreakdownQuery = ( { projectRef, connectionString }: DiskBreakdownVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - configKeys.diskBreakdown(projectRef), - ({ signal }) => getDiskBreakdown({ projectRef, connectionString }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: configKeys.diskBreakdown(projectRef), + queryFn: ({ signal }) => getDiskBreakdown({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/config/disk-utilization-query.ts b/apps/studio/data/config/disk-utilization-query.ts index 5d8b786f3e8d3..3e7a5f394f00e 100644 --- a/apps/studio/data/config/disk-utilization-query.ts +++ b/apps/studio/data/config/disk-utilization-query.ts @@ -33,8 +33,9 @@ export const useDiskUtilizationQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - configKeys.diskUtilization(projectRef), - ({ signal }) => getDiskUtilization({ projectRef }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: configKeys.diskUtilization(projectRef), + queryFn: ({ signal }) => getDiskUtilization({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/config/jwt-secret-update-mutation.ts b/apps/studio/data/config/jwt-secret-update-mutation.ts index 672ce8d9ab6fd..d3debe12df6cf 100644 --- a/apps/studio/data/config/jwt-secret-update-mutation.ts +++ b/apps/studio/data/config/jwt-secret-update-mutation.ts @@ -43,18 +43,16 @@ export const useJwtSecretUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (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) { - await onError?.(data, variables, context) - }, - ...options, - } - ) + return useMutation({ + mutationFn: (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) { + await onError?.(data, variables, context) + }, + ...options, + }) } diff --git a/apps/studio/data/config/jwt-secret-updating-status-query.ts b/apps/studio/data/config/jwt-secret-updating-status-query.ts index 40decc0021519..3f0a7167c876a 100644 --- a/apps/studio/data/config/jwt-secret-updating-status-query.ts +++ b/apps/studio/data/config/jwt-secret-updating-status-query.ts @@ -53,26 +53,24 @@ export const useJwtSecretUpdatingStatusQuery = { const client = useQueryClient() - return useQuery( - configKeys.jwtSecretUpdatingStatus(projectRef), - ({ signal }) => getJwtSecretUpdatingStatus({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - refetchInterval(data) { - if (!data) { - return false - } + return useQuery({ + queryKey: configKeys.jwtSecretUpdatingStatus(projectRef), + queryFn: ({ signal }) => getJwtSecretUpdatingStatus({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + refetchInterval(data) { + if (!data) { + return false + } - const { jwtSecretUpdateStatus } = data as unknown as JwtSecretUpdatingStatusResponse + const { jwtSecretUpdateStatus } = data as unknown as JwtSecretUpdatingStatusResponse - const interval = jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updating ? 1000 : false + const interval = jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updating ? 1000 : false - return interval - }, - onSuccess() { - client.invalidateQueries(configKeys.postgrest(projectRef)) - }, - ...options, - } - ) + return interval + }, + onSuccess() { + client.invalidateQueries(configKeys.postgrest(projectRef)) + }, + ...options, + }) } diff --git a/apps/studio/data/config/project-compliance-config-mutation.ts b/apps/studio/data/config/project-compliance-config-mutation.ts index 89317a31cf624..5e8740fcf8d85 100644 --- a/apps/studio/data/config/project-compliance-config-mutation.ts +++ b/apps/studio/data/config/project-compliance-config-mutation.ts @@ -37,22 +37,20 @@ export const useComplianceConfigUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateComplianceConfig(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(configKeys.settingsV2(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update project compliance configuration: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateComplianceConfig(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(configKeys.settingsV2(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update project compliance configuration: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/config/project-creation-postgres-versions-query.ts b/apps/studio/data/config/project-creation-postgres-versions-query.ts index 649d3d82279c3..1f3ecfdf9cc3b 100644 --- a/apps/studio/data/config/project-creation-postgres-versions-query.ts +++ b/apps/studio/data/config/project-creation-postgres-versions-query.ts @@ -43,19 +43,17 @@ export const useProjectCreationPostgresVersionsQuery = = {} ) => { - return useQuery( - configKeys.projectCreationPostgresVersions(organizationSlug, cloudProvider, dbRegion), - ({ signal }) => + return useQuery({ + queryKey: configKeys.projectCreationPostgresVersions(organizationSlug, cloudProvider, dbRegion), + queryFn: ({ signal }) => getPostgresCreationVersions({ organizationSlug, cloudProvider, dbRegion }, signal), - { - enabled: - enabled && - typeof organizationSlug !== 'undefined' && - organizationSlug !== '_' && - typeof dbRegion !== 'undefined', - ...options, - } - ) + enabled: + enabled && + typeof organizationSlug !== 'undefined' && + organizationSlug !== '_' && + typeof dbRegion !== 'undefined', + ...options, + }) } export const useAvailableOrioleImageVersion = ( diff --git a/apps/studio/data/config/project-disk-resize-mutation.ts b/apps/studio/data/config/project-disk-resize-mutation.ts index 29b63ca358c0a..c5e81ae511dbb 100644 --- a/apps/studio/data/config/project-disk-resize-mutation.ts +++ b/apps/studio/data/config/project-disk-resize-mutation.ts @@ -40,25 +40,23 @@ export const useProjectDiskResizeMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => resizeProjectDisk(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - queryClient.setQueriesData(usageKeys.usage(projectRef), (prev: any) => { - if (!prev) return prev - 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, - } - ) + return useMutation({ + mutationFn: (vars) => resizeProjectDisk(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + queryClient.setQueriesData(usageKeys.usage(projectRef), (prev: any) => { + if (!prev) return prev + 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/apps/studio/data/config/project-postgrest-config-query.ts b/apps/studio/data/config/project-postgrest-config-query.ts index fa31a67be0827..67c14ee48f1a8 100644 --- a/apps/studio/data/config/project-postgrest-config-query.ts +++ b/apps/studio/data/config/project-postgrest-config-query.ts @@ -39,11 +39,9 @@ export const useProjectPostgrestConfigQuery = = {} ) => - useQuery( - configKeys.postgrest(projectRef), - ({ signal }) => getProjectPostgrestConfig({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: configKeys.postgrest(projectRef), + queryFn: ({ signal }) => getProjectPostgrestConfig({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/config/project-postgrest-config-update-mutation.ts b/apps/studio/data/config/project-postgrest-config-update-mutation.ts index 7cc3fafc69416..510bbb08247da 100644 --- a/apps/studio/data/config/project-postgrest-config-update-mutation.ts +++ b/apps/studio/data/config/project-postgrest-config-update-mutation.ts @@ -59,7 +59,8 @@ export const useProjectPostgrestConfigUpdateMutation = ({ ProjectPostgrestConfigUpdateData, ResponseError, ProjectPostgrestConfigUpdateVariables - >((vars) => updateProjectPostgrestConfig(vars), { + >({ + mutationFn: (vars) => updateProjectPostgrestConfig(vars), async onSuccess(data, variables, context) { const { projectRef } = variables queryClient.invalidateQueries(configKeys.postgrest(projectRef)) diff --git a/apps/studio/data/config/project-settings-v2-query.ts b/apps/studio/data/config/project-settings-v2-query.ts index 759c0a784c732..2037b326d4644 100644 --- a/apps/studio/data/config/project-settings-v2-query.ts +++ b/apps/studio/data/config/project-settings-v2-query.ts @@ -49,19 +49,17 @@ export const useProjectSettingsV2Query = ( '*' ) - return useQuery( - configKeys.settingsV2(projectRef), - ({ signal }) => getProjectSettings({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - refetchInterval(_data) { - const data = _data as ProjectSettings | undefined - const apiKeys = data?.service_api_keys ?? [] - const interval = - canReadAPIKeys && data?.status !== 'INACTIVE' && apiKeys.length === 0 ? 2000 : 0 - return interval - }, - ...options, - } - ) + return useQuery({ + queryKey: configKeys.settingsV2(projectRef), + queryFn: ({ signal }) => getProjectSettings({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + refetchInterval(_data) { + const data = _data as ProjectSettings | undefined + const apiKeys = data?.service_api_keys ?? [] + const interval = + canReadAPIKeys && data?.status !== 'INACTIVE' && apiKeys.length === 0 ? 2000 : 0 + return interval + }, + ...options, + }) } diff --git a/apps/studio/data/config/project-storage-config-query.ts b/apps/studio/data/config/project-storage-config-query.ts index be158636207ae..82cc191b1949f 100644 --- a/apps/studio/data/config/project-storage-config-query.ts +++ b/apps/studio/data/config/project-storage-config-query.ts @@ -45,8 +45,9 @@ export const useProjectStorageConfigQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - configKeys.storage(projectRef), - ({ signal }) => getProjectStorageConfig({ projectRef }, signal), - { enabled: enabled && IS_PLATFORM && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: configKeys.storage(projectRef), + queryFn: ({ signal }) => getProjectStorageConfig({ projectRef }, signal), + enabled: enabled && IS_PLATFORM && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/config/project-storage-config-update-mutation.ts b/apps/studio/data/config/project-storage-config-update-mutation.ts index 3ded8ea532634..c5fd540656512 100644 --- a/apps/studio/data/config/project-storage-config-update-mutation.ts +++ b/apps/studio/data/config/project-storage-config-update-mutation.ts @@ -47,7 +47,8 @@ export const useProjectStorageConfigUpdateUpdateMutation = ({ ProjectStorageConfigUpdateUpdateData, ResponseError, ProjectStorageConfigUpdateUpdateVariables - >((vars) => updateProjectStorageConfigUpdate(vars), { + >({ + mutationFn: (vars) => updateProjectStorageConfigUpdate(vars), async onSuccess(data, variables, context) { const { projectRef } = variables await queryClient.invalidateQueries(configKeys.storage(projectRef)) diff --git a/apps/studio/data/config/project-temp-disable-read-only-mutation.ts b/apps/studio/data/config/project-temp-disable-read-only-mutation.ts index e5827a4f2db7e..3769f48ec594c 100644 --- a/apps/studio/data/config/project-temp-disable-read-only-mutation.ts +++ b/apps/studio/data/config/project-temp-disable-read-only-mutation.ts @@ -29,21 +29,19 @@ export const useDisableReadOnlyModeMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => tempDisableReadOnlyMode(vars), - { - async onSuccess(data, variables, context) { - setTimeout(() => queryClient.invalidateQueries(usageKeys.resourceWarnings()), 2000) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to disable read only mode: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => tempDisableReadOnlyMode(vars), + async onSuccess(data, variables, context) { + setTimeout(() => queryClient.invalidateQueries(usageKeys.resourceWarnings()), 2000) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to disable read only mode: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/config/project-unpause-postgres-versions-query.ts b/apps/studio/data/config/project-unpause-postgres-versions-query.ts index 72aa72dc42a86..9ddcc6b1d18e3 100644 --- a/apps/studio/data/config/project-unpause-postgres-versions-query.ts +++ b/apps/studio/data/config/project-unpause-postgres-versions-query.ts @@ -39,12 +39,10 @@ export const useProjectUnpausePostgresVersionsQuery = = {} ) => { - return useQuery( - configKeys.projectUnpausePostgresVersions(projectRef), - ({ signal }) => getPostgresUnpauseVersions({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + return useQuery({ + queryKey: configKeys.projectUnpausePostgresVersions(projectRef), + queryFn: ({ signal }) => getPostgresUnpauseVersions({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) } diff --git a/apps/studio/data/config/project-upgrade-eligibility-query.ts b/apps/studio/data/config/project-upgrade-eligibility-query.ts index 90ddc5962c359..53516146481b0 100644 --- a/apps/studio/data/config/project-upgrade-eligibility-query.ts +++ b/apps/studio/data/config/project-upgrade-eligibility-query.ts @@ -39,17 +39,15 @@ export const useProjectUpgradeEligibilityQuery = = {} ) => { const { data: project } = useProjectDetailQuery({ ref: projectRef }) - return useQuery( - configKeys.upgradeEligibility(projectRef), - ({ signal }) => getProjectUpgradeEligibility({ projectRef }, signal), - { - enabled: - enabled && - project !== undefined && - project.status === PROJECT_STATUS.ACTIVE_HEALTHY && - typeof projectRef !== 'undefined' && - IS_PLATFORM, - ...options, - } - ) + return useQuery({ + queryKey: configKeys.upgradeEligibility(projectRef), + queryFn: ({ signal }) => getProjectUpgradeEligibility({ projectRef }, signal), + enabled: + enabled && + project !== undefined && + project.status === PROJECT_STATUS.ACTIVE_HEALTHY && + typeof projectRef !== 'undefined' && + IS_PLATFORM, + ...options, + }) } diff --git a/apps/studio/data/config/project-upgrade-status-query.ts b/apps/studio/data/config/project-upgrade-status-query.ts index a4880d81502da..4489ced536fa8 100644 --- a/apps/studio/data/config/project-upgrade-status-query.ts +++ b/apps/studio/data/config/project-upgrade-status-query.ts @@ -42,33 +42,31 @@ export const useProjectUpgradingStatusQuery = { const client = useQueryClient() - return useQuery( - configKeys.upgradeStatus(projectRef), - ({ signal }) => getProjectUpgradingStatus({ projectRef, trackingId }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - refetchInterval(data) { - const response = data as unknown as ProjectUpgradingStatusData - if (!response) return false + return useQuery({ + queryKey: configKeys.upgradeStatus(projectRef), + queryFn: ({ signal }) => getProjectUpgradingStatus({ projectRef, trackingId }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + refetchInterval(data) { + const response = data as unknown as ProjectUpgradingStatusData + if (!response) return false - const interval = - // Transited to UPGRADING state via client, but job not yet picked up - (projectStatus === PROJECT_STATUS.UPGRADING && - response.databaseUpgradeStatus?.status !== DatabaseUpgradeStatus.Upgrading) || - // Project currently getting upgraded - response.databaseUpgradeStatus?.status === DatabaseUpgradeStatus.Upgrading - ? 5000 - : false + const interval = + // Transited to UPGRADING state via client, but job not yet picked up + (projectStatus === PROJECT_STATUS.UPGRADING && + response.databaseUpgradeStatus?.status !== DatabaseUpgradeStatus.Upgrading) || + // Project currently getting upgraded + response.databaseUpgradeStatus?.status === DatabaseUpgradeStatus.Upgrading + ? 5000 + : false - return interval - }, - onSuccess(data) { - const response = data as unknown as ProjectUpgradingStatusData - if (response.databaseUpgradeStatus?.status === DatabaseUpgradeStatus.Upgraded) { - client.invalidateQueries(configKeys.upgradeEligibility(projectRef)) - } - }, - ...options, - } - ) + return interval + }, + onSuccess(data) { + const response = data as unknown as ProjectUpgradingStatusData + if (response.databaseUpgradeStatus?.status === DatabaseUpgradeStatus.Upgraded) { + client.invalidateQueries(configKeys.upgradeEligibility(projectRef)) + } + }, + ...options, + }) } diff --git a/apps/studio/data/content-api/docs-error-codes-query.ts b/apps/studio/data/content-api/docs-error-codes-query.ts index 381c655222bb8..28b96a378d8f3 100644 --- a/apps/studio/data/content-api/docs-error-codes-query.ts +++ b/apps/studio/data/content-api/docs-error-codes-query.ts @@ -35,9 +35,10 @@ export const useErrorCodesQuery = ( ...options }: UseQueryOptions = {} ) => { - return useQuery( - contentApiKeys.errorCodes(variables), - ({ signal }) => getErrorCodeDescriptions(variables, signal), - { enabled, ...options } - ) + return useQuery({ + queryKey: contentApiKeys.errorCodes(variables), + queryFn: ({ signal }) => getErrorCodeDescriptions(variables, signal), + enabled, + ...options, + }) } diff --git a/apps/studio/data/content/content-count-query.ts b/apps/studio/data/content/content-count-query.ts index 513e42b54f85e..d7ae0eca0dde4 100644 --- a/apps/studio/data/content/content-count-query.ts +++ b/apps/studio/data/content/content-count-query.ts @@ -39,13 +39,11 @@ export const useContentCountQuery = ( { projectRef, type, name }: GetContentCountVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - contentKeys.count(projectRef, type, { + useQuery({ + queryKey: contentKeys.count(projectRef, type, { name, }), - ({ signal }) => getContentCount({ projectRef, type, name }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + queryFn: ({ signal }) => getContentCount({ projectRef, type, name }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/content/content-delete-mutation.ts b/apps/studio/data/content/content-delete-mutation.ts index a8110e1e8f668..a502816b0837f 100644 --- a/apps/studio/data/content/content-delete-mutation.ts +++ b/apps/studio/data/content/content-delete-mutation.ts @@ -36,26 +36,24 @@ export const useContentDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (args) => deleteContents(args), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await Promise.all([ - queryClient.invalidateQueries(contentKeys.allContentLists(projectRef)), - queryClient.invalidateQueries(contentKeys.infiniteList(projectRef)), - ]) - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete contents: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (args) => deleteContents(args), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await Promise.all([ + queryClient.invalidateQueries(contentKeys.allContentLists(projectRef)), + queryClient.invalidateQueries(contentKeys.infiniteList(projectRef)), + ]) + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete contents: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/content/content-id-query.ts b/apps/studio/data/content/content-id-query.ts index d2db7a33799f1..e9d79ec8f61c1 100644 --- a/apps/studio/data/content/content-id-query.ts +++ b/apps/studio/data/content/content-id-query.ts @@ -37,11 +37,9 @@ export const useContentIdQuery = ( { projectRef, id }: { projectRef?: string; id?: string }, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - contentKeys.resource(projectRef, id), - ({ signal }) => getContentById({ projectRef, id }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: contentKeys.resource(projectRef, id), + queryFn: ({ signal }) => getContentById({ projectRef, id }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/content/content-insert-mutation.ts b/apps/studio/data/content/content-insert-mutation.ts index b1df9f45bdc87..0d25a50b27d8e 100644 --- a/apps/studio/data/content/content-insert-mutation.ts +++ b/apps/studio/data/content/content-insert-mutation.ts @@ -52,22 +52,20 @@ export const useContentInsertMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (args) => insertContent(args), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(contentKeys.allContentLists(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to insert content: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (args) => insertContent(args), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(contentKeys.allContentLists(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to insert content: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/content/content-query.ts b/apps/studio/data/content/content-query.ts index 8b019e89591cd..5ca19b335b7a2 100644 --- a/apps/studio/data/content/content-query.ts +++ b/apps/studio/data/content/content-query.ts @@ -61,8 +61,9 @@ export const useContentQuery = ( { projectRef, type, name, limit }: GetContentVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - contentKeys.list(projectRef, { type, name, limit }), - ({ signal }) => getContent({ projectRef, type, name, limit }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: contentKeys.list(projectRef, { type, name, limit }), + queryFn: ({ signal }) => getContent({ projectRef, type, name, limit }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/content/content-upsert-mutation.ts b/apps/studio/data/content/content-upsert-mutation.ts index e6dc7bc93e9e5..685cab48e36ae 100644 --- a/apps/studio/data/content/content-upsert-mutation.ts +++ b/apps/studio/data/content/content-upsert-mutation.ts @@ -46,27 +46,25 @@ export const useContentUpsertMutation = ({ } = {}) => { const queryClient = useQueryClient() - return useMutation( - (args) => upsertContent(args), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - if (invalidateQueriesOnSuccess) { - await Promise.all([ - queryClient.invalidateQueries(contentKeys.allContentLists(projectRef)), - queryClient.invalidateQueries(contentKeys.infiniteList(projectRef)), - ]) - } - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to insert content: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (args) => upsertContent(args), + async onSuccess(data, variables, context) { + const { projectRef } = variables + if (invalidateQueriesOnSuccess) { + await Promise.all([ + queryClient.invalidateQueries(contentKeys.allContentLists(projectRef)), + queryClient.invalidateQueries(contentKeys.infiniteList(projectRef)), + ]) + } + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to insert content: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/content/sql-folder-create-mutation.ts b/apps/studio/data/content/sql-folder-create-mutation.ts index 267344eda531f..fe8435c254517 100644 --- a/apps/studio/data/content/sql-folder-create-mutation.ts +++ b/apps/studio/data/content/sql-folder-create-mutation.ts @@ -43,24 +43,22 @@ export const useSQLSnippetFolderCreateMutation = ({ } = {}) => { const queryClient = useQueryClient() - return useMutation( - (args) => createSQLSnippetFolder(args), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - if (invalidateQueriesOnSuccess) { - await queryClient.invalidateQueries(contentKeys.folders(projectRef)) - } - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create folder: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (args) => createSQLSnippetFolder(args), + async onSuccess(data, variables, context) { + const { projectRef } = variables + if (invalidateQueriesOnSuccess) { + await queryClient.invalidateQueries(contentKeys.folders(projectRef)) + } + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create folder: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/content/sql-folder-update-mutation.ts b/apps/studio/data/content/sql-folder-update-mutation.ts index c639b74e58a84..c2664a8215249 100644 --- a/apps/studio/data/content/sql-folder-update-mutation.ts +++ b/apps/studio/data/content/sql-folder-update-mutation.ts @@ -44,24 +44,22 @@ export const useSQLSnippetFolderCreateMutation = ({ } = {}) => { const queryClient = useQueryClient() - return useMutation( - (args) => updateSQLSnippetFolder(args), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - if (invalidateQueriesOnSuccess) { - await queryClient.invalidateQueries(contentKeys.folders(projectRef)) - } - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update folder: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (args) => updateSQLSnippetFolder(args), + async onSuccess(data, variables, context) { + const { projectRef } = variables + if (invalidateQueriesOnSuccess) { + await queryClient.invalidateQueries(contentKeys.folders(projectRef)) + } + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update folder: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/content/sql-folders-delete-mutation.ts b/apps/studio/data/content/sql-folders-delete-mutation.ts index 25caae68a190e..27db3961e47e2 100644 --- a/apps/studio/data/content/sql-folders-delete-mutation.ts +++ b/apps/studio/data/content/sql-folders-delete-mutation.ts @@ -39,24 +39,22 @@ export const useSQLSnippetFoldersDeleteMutation = ({ } = {}) => { const queryClient = useQueryClient() - return useMutation( - (args) => deleteSQLSnippetFolders(args), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - if (invalidateQueriesOnSuccess) { - await queryClient.invalidateQueries(contentKeys.folders(projectRef)) - } - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete folder: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (args) => deleteSQLSnippetFolders(args), + async onSuccess(data, variables, context) { + const { projectRef } = variables + if (invalidateQueriesOnSuccess) { + await queryClient.invalidateQueries(contentKeys.folders(projectRef)) + } + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete folder: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/custom-domains/check-cname-mutation.ts b/apps/studio/data/custom-domains/check-cname-mutation.ts index 183a53514d5d7..a85afaf06590c 100644 --- a/apps/studio/data/custom-domains/check-cname-mutation.ts +++ b/apps/studio/data/custom-domains/check-cname-mutation.ts @@ -50,20 +50,18 @@ export const useCheckCNAMERecordMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => checkCNAMERecord(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to check CNAME record: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => checkCNAMERecord(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to check CNAME record: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/custom-domains/custom-domains-activate-mutation.ts b/apps/studio/data/custom-domains/custom-domains-activate-mutation.ts index 3224dfb1f9195..d9c2e6a797903 100644 --- a/apps/studio/data/custom-domains/custom-domains-activate-mutation.ts +++ b/apps/studio/data/custom-domains/custom-domains-activate-mutation.ts @@ -30,22 +30,20 @@ export const useCustomDomainActivateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => activateCustomDomain(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(customDomainKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to activate custom domain: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => activateCustomDomain(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(customDomainKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to activate custom domain: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/custom-domains/custom-domains-create-mutation.ts b/apps/studio/data/custom-domains/custom-domains-create-mutation.ts index 5e3cef99010e7..2635ef561a15e 100644 --- a/apps/studio/data/custom-domains/custom-domains-create-mutation.ts +++ b/apps/studio/data/custom-domains/custom-domains-create-mutation.ts @@ -35,22 +35,20 @@ export const useCustomDomainCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createCustomDomain(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(customDomainKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create custom domain: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createCustomDomain(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(customDomainKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create custom domain: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/custom-domains/custom-domains-delete-mutation.ts b/apps/studio/data/custom-domains/custom-domains-delete-mutation.ts index 7a9568d8da5b0..d4f20311908b5 100644 --- a/apps/studio/data/custom-domains/custom-domains-delete-mutation.ts +++ b/apps/studio/data/custom-domains/custom-domains-delete-mutation.ts @@ -32,32 +32,30 @@ export const useCustomDomainDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteCustomDomain(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - - // we manually setQueriesData here instead of using - // the standard invalidateQueries is the custom domains - // endpoint doesn't immediately return the new state - queryClient.setQueriesData(customDomainKeys.list(projectRef), () => { - return { - customDomain: null, - status: '0_no_hostname_configured', - } - }) - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete custom domain: ${data.message}`) - } else { - onError(data, variables, context) + return useMutation({ + mutationFn: (vars) => deleteCustomDomain(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + + // we manually setQueriesData here instead of using + // the standard invalidateQueries is the custom domains + // endpoint doesn't immediately return the new state + queryClient.setQueriesData(customDomainKeys.list(projectRef), () => { + return { + customDomain: null, + status: '0_no_hostname_configured', } - }, - ...options, - } - ) + }) + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete custom domain: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/custom-domains/custom-domains-query.ts b/apps/studio/data/custom-domains/custom-domains-query.ts index 8c8488c46852e..8f9e757c28082 100644 --- a/apps/studio/data/custom-domains/custom-domains-query.ts +++ b/apps/studio/data/custom-domains/custom-domains-query.ts @@ -110,12 +110,10 @@ export const useCustomDomainsQuery = ( const { data } = useProjectAddonsQuery({ projectRef }) const hasCustomDomainsAddon = !!data?.selected_addons.find((x) => x.type === 'custom_domain') - return useQuery( - customDomainKeys.list(projectRef), - ({ signal }) => getCustomDomains({ projectRef }, signal), - { - enabled: enabled && IS_PLATFORM && typeof projectRef !== 'undefined' && hasCustomDomainsAddon, - ...options, - } - ) + return useQuery({ + queryKey: customDomainKeys.list(projectRef), + queryFn: ({ signal }) => getCustomDomains({ projectRef }, signal), + enabled: enabled && IS_PLATFORM && typeof projectRef !== 'undefined' && hasCustomDomainsAddon, + ...options, + }) } diff --git a/apps/studio/data/custom-domains/custom-domains-reverify-mutation.ts b/apps/studio/data/custom-domains/custom-domains-reverify-mutation.ts index e050146d02b1f..b3a4755096258 100644 --- a/apps/studio/data/custom-domains/custom-domains-reverify-mutation.ts +++ b/apps/studio/data/custom-domains/custom-domains-reverify-mutation.ts @@ -30,22 +30,20 @@ export const useCustomDomainReverifyMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => reverifyCustomDomain(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(customDomainKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to reverify custom domain: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => reverifyCustomDomain(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(customDomainKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to reverify custom domain: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-columns/database-column-create-mutation.ts b/apps/studio/data/database-columns/database-column-create-mutation.ts index 74bc316d5d3d7..38f57e0addc36 100644 --- a/apps/studio/data/database-columns/database-column-create-mutation.ts +++ b/apps/studio/data/database-columns/database-column-create-mutation.ts @@ -58,20 +58,18 @@ export const useDatabaseColumnCreateMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => createDatabaseColumn(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create database column: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createDatabaseColumn(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create database column: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-columns/database-column-delete-mutation.ts b/apps/studio/data/database-columns/database-column-delete-mutation.ts index 41325ebb3af53..2052406998658 100644 --- a/apps/studio/data/database-columns/database-column-delete-mutation.ts +++ b/apps/studio/data/database-columns/database-column-delete-mutation.ts @@ -47,40 +47,38 @@ export const useDatabaseColumnDeleteMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteDatabaseColumn(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, column } = variables - await Promise.all([ - // refetch all entities in the sidebar because deleting a column may regenerate a view (and change its id) - queryClient.invalidateQueries(entityTypeKeys.list(projectRef)), - queryClient.invalidateQueries( - databaseKeys.foreignKeyConstraints(projectRef, column.schema) - ), - queryClient.invalidateQueries(tableEditorKeys.tableEditor(projectRef, column.table_id)), - queryClient.invalidateQueries(databaseKeys.tableDefinition(projectRef, column.table_id)), - // invalidate all views from this schema, not sure if this is needed since you can't actually delete a column - // which has a view dependent on it - queryClient.invalidateQueries(viewKeys.listBySchema(projectRef, column.schema)), - ]) + return useMutation({ + mutationFn: (vars) => deleteDatabaseColumn(vars), + async onSuccess(data, variables, context) { + const { projectRef, column } = variables + await Promise.all([ + // refetch all entities in the sidebar because deleting a column may regenerate a view (and change its id) + queryClient.invalidateQueries(entityTypeKeys.list(projectRef)), + queryClient.invalidateQueries( + databaseKeys.foreignKeyConstraints(projectRef, column.schema) + ), + queryClient.invalidateQueries(tableEditorKeys.tableEditor(projectRef, column.table_id)), + queryClient.invalidateQueries(databaseKeys.tableDefinition(projectRef, column.table_id)), + // invalidate all views from this schema, not sure if this is needed since you can't actually delete a column + // which has a view dependent on it + queryClient.invalidateQueries(viewKeys.listBySchema(projectRef, column.schema)), + ]) - // We need to invalidate tableRowsAndCount after tableEditor - // to ensure the query sent is correct - await queryClient.invalidateQueries( - tableRowKeys.tableRowsAndCount(projectRef, column.table_id) - ) + // We need to invalidate tableRowsAndCount after tableEditor + // to ensure the query sent is correct + await queryClient.invalidateQueries( + tableRowKeys.tableRowsAndCount(projectRef, column.table_id) + ) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete database column: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete database column: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-columns/database-column-update-mutation.ts b/apps/studio/data/database-columns/database-column-update-mutation.ts index ac3db6c0772ec..419f25cb3724d 100644 --- a/apps/studio/data/database-columns/database-column-update-mutation.ts +++ b/apps/studio/data/database-columns/database-column-update-mutation.ts @@ -72,20 +72,18 @@ export const useDatabaseColumnUpdateMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => updateDatabaseColumn(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update database column: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateDatabaseColumn(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update database column: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-cron-jobs/database-cron-job-query.ts b/apps/studio/data/database-cron-jobs/database-cron-job-query.ts index cb78d893d6508..3fe4524b17ac4 100644 --- a/apps/studio/data/database-cron-jobs/database-cron-job-query.ts +++ b/apps/studio/data/database-cron-jobs/database-cron-job-query.ts @@ -42,14 +42,12 @@ export const useCronJobQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databaseCronJobsKeys.job(projectRef, id ?? name), - () => getDatabaseCronJob({ projectRef, connectionString, id }), - { - enabled: - enabled && - typeof projectRef !== 'undefined' && - (typeof id !== 'undefined' || typeof name !== 'undefined'), - ...options, - } - ) + useQuery({ + queryKey: databaseCronJobsKeys.job(projectRef, id ?? name), + queryFn: () => getDatabaseCronJob({ projectRef, connectionString, id }), + enabled: + enabled && + typeof projectRef !== 'undefined' && + (typeof id !== 'undefined' || typeof name !== 'undefined'), + ...options, + }) diff --git a/apps/studio/data/database-cron-jobs/database-cron-job-run-mutation.ts b/apps/studio/data/database-cron-jobs/database-cron-job-run-mutation.ts index 2e88d0ed8a02c..c4d416dde142f 100644 --- a/apps/studio/data/database-cron-jobs/database-cron-job-run-mutation.ts +++ b/apps/studio/data/database-cron-jobs/database-cron-job-run-mutation.ts @@ -47,20 +47,18 @@ export const useDatabaseCronJobRunCommandMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => runDatabaseCronJobCommand(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to run cron job command: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => runDatabaseCronJobCommand(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to run cron job command: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-cron-jobs/database-cron-jobs-count-query.ts b/apps/studio/data/database-cron-jobs/database-cron-jobs-count-query.ts index 70ad18caa62f9..85813f9b2407f 100644 --- a/apps/studio/data/database-cron-jobs/database-cron-jobs-count-query.ts +++ b/apps/studio/data/database-cron-jobs/database-cron-jobs-count-query.ts @@ -35,11 +35,9 @@ export const useCronJobsCountQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databaseCronJobsKeys.count(projectRef), - () => getDatabaseCronJobsCount({ projectRef, connectionString }), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseCronJobsKeys.count(projectRef), + queryFn: () => getDatabaseCronJobsCount({ projectRef, connectionString }), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database-cron-jobs/database-cron-jobs-create-mutation.ts b/apps/studio/data/database-cron-jobs/database-cron-jobs-create-mutation.ts index ab918eb91d275..f751ef6dd425f 100644 --- a/apps/studio/data/database-cron-jobs/database-cron-jobs-create-mutation.ts +++ b/apps/studio/data/database-cron-jobs/database-cron-jobs-create-mutation.ts @@ -40,29 +40,27 @@ export const useDatabaseCronJobCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createDatabaseCronJob(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, searchTerm, identifier } = variables + return useMutation({ + mutationFn: (vars) => createDatabaseCronJob(vars), + async onSuccess(data, variables, context) { + const { projectRef, searchTerm, identifier } = variables - await Promise.all([ - queryClient.invalidateQueries(databaseCronJobsKeys.listInfinite(projectRef, searchTerm)), - ...(!!identifier - ? [queryClient.invalidateQueries(databaseCronJobsKeys.job(projectRef, identifier))] - : []), - ]) + await Promise.all([ + queryClient.invalidateQueries(databaseCronJobsKeys.listInfinite(projectRef, searchTerm)), + ...(!!identifier + ? [queryClient.invalidateQueries(databaseCronJobsKeys.job(projectRef, identifier))] + : []), + ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create database cron job: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create database cron job: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-cron-jobs/database-cron-jobs-delete-mutation.ts b/apps/studio/data/database-cron-jobs/database-cron-jobs-delete-mutation.ts index d38414ec968d9..85780c4499405 100644 --- a/apps/studio/data/database-cron-jobs/database-cron-jobs-delete-mutation.ts +++ b/apps/studio/data/database-cron-jobs/database-cron-jobs-delete-mutation.ts @@ -39,24 +39,20 @@ export const useDatabaseCronJobDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteDatabaseCronJob(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, searchTerm } = variables - await queryClient.invalidateQueries( - databaseCronJobsKeys.listInfinite(projectRef, searchTerm) - ) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete database cron job: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteDatabaseCronJob(vars), + async onSuccess(data, variables, context) { + const { projectRef, searchTerm } = variables + await queryClient.invalidateQueries(databaseCronJobsKeys.listInfinite(projectRef, searchTerm)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete database cron job: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-cron-jobs/database-cron-jobs-toggle-mutation.ts b/apps/studio/data/database-cron-jobs/database-cron-jobs-toggle-mutation.ts index da8ec6780fd21..78536ec33be2a 100644 --- a/apps/studio/data/database-cron-jobs/database-cron-jobs-toggle-mutation.ts +++ b/apps/studio/data/database-cron-jobs/database-cron-jobs-toggle-mutation.ts @@ -41,24 +41,20 @@ export const useDatabaseCronJobToggleMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => toggleDatabaseCronJob(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, searchTerm } = variables - await queryClient.invalidateQueries( - databaseCronJobsKeys.listInfinite(projectRef, searchTerm) - ) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to toggle database cron job: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => toggleDatabaseCronJob(vars), + async onSuccess(data, variables, context) { + const { projectRef, searchTerm } = variables + await queryClient.invalidateQueries(databaseCronJobsKeys.listInfinite(projectRef, searchTerm)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to toggle database cron job: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-cron-jobs/database-cron-timezone-query.ts b/apps/studio/data/database-cron-jobs/database-cron-timezone-query.ts index 159ed28585821..0047e57c3c4fa 100644 --- a/apps/studio/data/database-cron-jobs/database-cron-timezone-query.ts +++ b/apps/studio/data/database-cron-jobs/database-cron-timezone-query.ts @@ -28,11 +28,9 @@ export const useCronTimezoneQuery = ( { projectRef, connectionString }: DatabaseCronJobsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - databaseCronJobsKeys.timezone(projectRef), - () => getDatabaseCronTimezone({ projectRef, connectionString }), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseCronJobsKeys.timezone(projectRef), + queryFn: () => getDatabaseCronTimezone({ projectRef, connectionString }), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database-extensions/database-extension-disable-mutation.ts b/apps/studio/data/database-extensions/database-extension-disable-mutation.ts index 7f1723db36518..7e3121d6b17a3 100644 --- a/apps/studio/data/database-extensions/database-extension-disable-mutation.ts +++ b/apps/studio/data/database-extensions/database-extension-disable-mutation.ts @@ -54,7 +54,8 @@ export const useDatabaseExtensionDisableMutation = ({ DatabaseExtensionDisableData, ResponseError, DatabaseExtensionDisableVariables - >((vars) => disableDatabaseExtension(vars), { + >({ + mutationFn: (vars) => disableDatabaseExtension(vars), async onSuccess(data, variables, context) { const { projectRef } = variables await Promise.all([ diff --git a/apps/studio/data/database-extensions/database-extension-enable-mutation.ts b/apps/studio/data/database-extensions/database-extension-enable-mutation.ts index f7b771982986a..af1df84bd542d 100644 --- a/apps/studio/data/database-extensions/database-extension-enable-mutation.ts +++ b/apps/studio/data/database-extensions/database-extension-enable-mutation.ts @@ -53,25 +53,23 @@ export const useDatabaseExtensionEnableMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => enableDatabaseExtension(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await Promise.all([ - queryClient.invalidateQueries(databaseExtensionsKeys.list(projectRef)), - queryClient.invalidateQueries(configKeys.upgradeEligibility(projectRef)), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to enable database extension: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => enableDatabaseExtension(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await Promise.all([ + queryClient.invalidateQueries(databaseExtensionsKeys.list(projectRef)), + queryClient.invalidateQueries(configKeys.upgradeEligibility(projectRef)), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to enable database extension: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-extensions/database-extensions-query.ts b/apps/studio/data/database-extensions/database-extensions-query.ts index 5ea9faf1ebaa0..0d4ee6abbd68c 100644 --- a/apps/studio/data/database-extensions/database-extensions-query.ts +++ b/apps/studio/data/database-extensions/database-extensions-query.ts @@ -55,12 +55,10 @@ export const useDatabaseExtensionsQuery = ( const { data: project } = useSelectedProjectQuery() const isActive = project?.status === PROJECT_STATUS.ACTIVE_HEALTHY - return useQuery( - databaseExtensionsKeys.list(projectRef), - ({ signal }) => getDatabaseExtensions({ projectRef, connectionString }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && isActive, - ...options, - } - ) + return useQuery({ + queryKey: databaseExtensionsKeys.list(projectRef), + queryFn: ({ signal }) => getDatabaseExtensions({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && isActive, + ...options, + }) } diff --git a/apps/studio/data/database-functions/database-functions-create-mutation.ts b/apps/studio/data/database-functions/database-functions-create-mutation.ts index c70fbb08f3cc3..aa1749ef5b226 100644 --- a/apps/studio/data/database-functions/database-functions-create-mutation.ts +++ b/apps/studio/data/database-functions/database-functions-create-mutation.ts @@ -42,22 +42,20 @@ export const useDatabaseFunctionCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createDatabaseFunction(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(databaseKeys.databaseFunctions(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create database function: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createDatabaseFunction(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(databaseKeys.databaseFunctions(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create database function: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-functions/database-functions-delete-mutation.ts b/apps/studio/data/database-functions/database-functions-delete-mutation.ts index 4610ca899dfd5..1e168d5b7314f 100644 --- a/apps/studio/data/database-functions/database-functions-delete-mutation.ts +++ b/apps/studio/data/database-functions/database-functions-delete-mutation.ts @@ -43,22 +43,20 @@ export const useDatabaseFunctionDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteDatabaseFunction(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(databaseKeys.databaseFunctions(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete database function: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteDatabaseFunction(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(databaseKeys.databaseFunctions(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete database function: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-functions/database-functions-query.ts b/apps/studio/data/database-functions/database-functions-query.ts index cef5dc7ddb31d..5d8cec8a4484f 100644 --- a/apps/studio/data/database-functions/database-functions-query.ts +++ b/apps/studio/data/database-functions/database-functions-query.ts @@ -45,11 +45,9 @@ export const useDatabaseFunctionsQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.databaseFunctions(projectRef), - ({ signal }) => getDatabaseFunctions({ projectRef, connectionString }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.databaseFunctions(projectRef), + queryFn: ({ signal }) => getDatabaseFunctions({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database-functions/database-functions-update-mutation.ts b/apps/studio/data/database-functions/database-functions-update-mutation.ts index a088e08b08df4..9fc0518a79561 100644 --- a/apps/studio/data/database-functions/database-functions-update-mutation.ts +++ b/apps/studio/data/database-functions/database-functions-update-mutation.ts @@ -45,22 +45,20 @@ export const useDatabaseFunctionUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateDatabaseFunction(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(databaseKeys.databaseFunctions(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update database function: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateDatabaseFunction(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(databaseKeys.databaseFunctions(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update database function: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-indexes/index-create-mutation.ts b/apps/studio/data/database-indexes/index-create-mutation.ts index efb58d18c32b2..c0d03c1fd418a 100644 --- a/apps/studio/data/database-indexes/index-create-mutation.ts +++ b/apps/studio/data/database-indexes/index-create-mutation.ts @@ -51,22 +51,20 @@ export const useDatabaseIndexCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createDatabaseIndex(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(databaseIndexesKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create database index: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createDatabaseIndex(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(databaseIndexesKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create database index: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-indexes/index-delete-mutation.ts b/apps/studio/data/database-indexes/index-delete-mutation.ts index 47dea94fe6d04..79c3f22b337de 100644 --- a/apps/studio/data/database-indexes/index-delete-mutation.ts +++ b/apps/studio/data/database-indexes/index-delete-mutation.ts @@ -42,22 +42,20 @@ export const useDatabaseIndexDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteDatabaseIndex(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(databaseIndexesKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete database index: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteDatabaseIndex(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(databaseIndexesKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete database index: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-indexes/indexes-query.ts b/apps/studio/data/database-indexes/indexes-query.ts index 840250bd002b9..63c46d52af92a 100644 --- a/apps/studio/data/database-indexes/indexes-query.ts +++ b/apps/studio/data/database-indexes/indexes-query.ts @@ -57,11 +57,9 @@ export const useIndexesQuery = ( { projectRef, connectionString, schema }: IndexesVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - databaseIndexesKeys.list(projectRef, schema), - ({ signal }) => getIndexes({ projectRef, connectionString, schema }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof schema !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseIndexesKeys.list(projectRef, schema), + queryFn: ({ signal }) => getIndexes({ projectRef, connectionString, schema }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && typeof schema !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database-policies/database-policies-query.ts b/apps/studio/data/database-policies/database-policies-query.ts index f7de486f42941..86112fc583d80 100644 --- a/apps/studio/data/database-policies/database-policies-query.ts +++ b/apps/studio/data/database-policies/database-policies-query.ts @@ -56,12 +56,10 @@ export const useDatabasePoliciesQuery = ( const { data: project } = useSelectedProjectQuery() const isActive = project?.status === PROJECT_STATUS.ACTIVE_HEALTHY - return useQuery( - databasePoliciesKeys.list(projectRef, schema), - ({ signal }) => getDatabasePolicies({ projectRef, connectionString, schema }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && isActive, - ...options, - } - ) + return useQuery({ + queryKey: databasePoliciesKeys.list(projectRef, schema), + queryFn: ({ signal }) => getDatabasePolicies({ projectRef, connectionString, schema }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && isActive, + ...options, + }) } diff --git a/apps/studio/data/database-policies/database-policy-create-mutation.ts b/apps/studio/data/database-policies/database-policy-create-mutation.ts index ec458a81e84b8..b218c4a32dc30 100644 --- a/apps/studio/data/database-policies/database-policy-create-mutation.ts +++ b/apps/studio/data/database-policies/database-policy-create-mutation.ts @@ -46,22 +46,20 @@ export const useDatabasePolicyCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createDatabasePolicy(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(databasePoliciesKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create database policy: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createDatabasePolicy(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(databasePoliciesKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create database policy: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-policies/database-policy-delete-mutation.ts b/apps/studio/data/database-policies/database-policy-delete-mutation.ts index e6acc542eb2c8..effb26c5c0bcc 100644 --- a/apps/studio/data/database-policies/database-policy-delete-mutation.ts +++ b/apps/studio/data/database-policies/database-policy-delete-mutation.ts @@ -48,22 +48,20 @@ export const useDatabasePolicyDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteDatabasePolicy(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(databasePoliciesKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete database policy: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteDatabasePolicy(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(databasePoliciesKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete database policy: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-policies/database-policy-update-mutation.ts b/apps/studio/data/database-policies/database-policy-update-mutation.ts index b07e82406b1e8..8a24b5307ccb7 100644 --- a/apps/studio/data/database-policies/database-policy-update-mutation.ts +++ b/apps/studio/data/database-policies/database-policy-update-mutation.ts @@ -55,22 +55,20 @@ export const useDatabasePolicyUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateDatabasePolicy(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(databasePoliciesKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update database policy: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateDatabasePolicy(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(databasePoliciesKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update database policy: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-publications/database-publications-create-mutation.ts b/apps/studio/data/database-publications/database-publications-create-mutation.ts index 16d98dfa6de8c..993a8a96d7ef4 100644 --- a/apps/studio/data/database-publications/database-publications-create-mutation.ts +++ b/apps/studio/data/database-publications/database-publications-create-mutation.ts @@ -66,7 +66,8 @@ export const useDatabasePublicationCreateMutation = ({ DatabasePublicationCreateData, ResponseError, DatabasePublicationCreateVariables - >((vars) => createDatabasePublication(vars), { + >({ + mutationFn: (vars) => createDatabasePublication(vars), async onSuccess(data, variables, context) { const { projectRef } = variables await queryClient.invalidateQueries(databasePublicationsKeys.list(projectRef)) diff --git a/apps/studio/data/database-publications/database-publications-query.ts b/apps/studio/data/database-publications/database-publications-query.ts index 616efce369289..0d889ebab98b0 100644 --- a/apps/studio/data/database-publications/database-publications-query.ts +++ b/apps/studio/data/database-publications/database-publications-query.ts @@ -46,11 +46,9 @@ export const useDatabasePublicationsQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databasePublicationsKeys.list(projectRef), - ({ signal }) => getDatabasePublications({ projectRef, connectionString }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databasePublicationsKeys.list(projectRef), + queryFn: ({ signal }) => getDatabasePublications({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database-publications/database-publications-update-mutation.ts b/apps/studio/data/database-publications/database-publications-update-mutation.ts index 3f219f1f535cd..7f9f9fb39abc9 100644 --- a/apps/studio/data/database-publications/database-publications-update-mutation.ts +++ b/apps/studio/data/database-publications/database-publications-update-mutation.ts @@ -65,7 +65,8 @@ export const useDatabasePublicationUpdateMutation = ({ DatabasePublicationUpdateData, ResponseError, DatabasePublicationUpdateVariables - >((vars) => updateDatabasePublication(vars), { + >({ + mutationFn: (vars) => updateDatabasePublication(vars), async onSuccess(data, variables, context) { const { projectRef } = variables await queryClient.invalidateQueries(databasePublicationsKeys.list(projectRef)) diff --git a/apps/studio/data/database-queues/database-queue-messages-archive-mutation.ts b/apps/studio/data/database-queues/database-queue-messages-archive-mutation.ts index a540def777cda..be4621bc6a633 100644 --- a/apps/studio/data/database-queues/database-queue-messages-archive-mutation.ts +++ b/apps/studio/data/database-queues/database-queue-messages-archive-mutation.ts @@ -48,7 +48,8 @@ export const useDatabaseQueueMessageArchiveMutation = ({ DatabaseQueueMessageArchiveData, ResponseError, DatabaseQueueMessageArchiveVariables - >((vars) => archiveDatabaseQueueMessage(vars), { + >({ + mutationFn: (vars) => archiveDatabaseQueueMessage(vars), async onSuccess(data, variables, context) { const { projectRef, queryName } = variables await queryClient.invalidateQueries( diff --git a/apps/studio/data/database-queues/database-queue-messages-delete-mutation.ts b/apps/studio/data/database-queues/database-queue-messages-delete-mutation.ts index 947a2e5ed79be..6cd51ca390c30 100644 --- a/apps/studio/data/database-queues/database-queue-messages-delete-mutation.ts +++ b/apps/studio/data/database-queues/database-queue-messages-delete-mutation.ts @@ -48,7 +48,8 @@ export const useDatabaseQueueMessageDeleteMutation = ({ DatabaseQueueMessageDeleteData, ResponseError, DatabaseQueueMessageDeleteVariables - >((vars) => deleteDatabaseQueueMessage(vars), { + >({ + mutationFn: (vars) => deleteDatabaseQueueMessage(vars), async onSuccess(data, variables, context) { const { projectRef, queueName } = variables await queryClient.invalidateQueries( diff --git a/apps/studio/data/database-queues/database-queue-messages-read-mutation.ts b/apps/studio/data/database-queues/database-queue-messages-read-mutation.ts index ba1055362e709..d451544cc5ba6 100644 --- a/apps/studio/data/database-queues/database-queue-messages-read-mutation.ts +++ b/apps/studio/data/database-queues/database-queue-messages-read-mutation.ts @@ -50,7 +50,8 @@ export const useDatabaseQueueMessageReadMutation = ({ DatabaseQueueMessageReadData, ResponseError, DatabaseQueueMessageReadVariables - >((vars) => readDatabaseQueueMessage(vars), { + >({ + mutationFn: (vars) => readDatabaseQueueMessage(vars), async onSuccess(data, variables, context) { const { projectRef, queryName } = variables await queryClient.invalidateQueries( diff --git a/apps/studio/data/database-queues/database-queue-messages-send-mutation.ts b/apps/studio/data/database-queues/database-queue-messages-send-mutation.ts index 23c5445b63bff..12e0a03ca1bb6 100644 --- a/apps/studio/data/database-queues/database-queue-messages-send-mutation.ts +++ b/apps/studio/data/database-queues/database-queue-messages-send-mutation.ts @@ -50,7 +50,8 @@ export const useDatabaseQueueMessageSendMutation = ({ DatabaseQueueMessageSendData, ResponseError, DatabaseQueueMessageSendVariables - >((vars) => sendDatabaseQueueMessage(vars), { + >({ + mutationFn: (vars) => sendDatabaseQueueMessage(vars), async onSuccess(data, variables, context) { const { projectRef, queueName } = variables await queryClient.invalidateQueries( diff --git a/apps/studio/data/database-queues/database-queues-create-mutation.ts b/apps/studio/data/database-queues/database-queues-create-mutation.ts index 04f190ddabf06..4866daee1aaaa 100644 --- a/apps/studio/data/database-queues/database-queues-create-mutation.ts +++ b/apps/studio/data/database-queues/database-queues-create-mutation.ts @@ -57,23 +57,21 @@ export const useDatabaseQueueCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createDatabaseQueue(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(databaseQueuesKeys.list(projectRef)) - queryClient.invalidateQueries(tableKeys.list(projectRef, 'pgmq')) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create database queue: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createDatabaseQueue(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(databaseQueuesKeys.list(projectRef)) + queryClient.invalidateQueries(tableKeys.list(projectRef, 'pgmq')) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create database queue: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-queues/database-queues-delete-mutation.ts b/apps/studio/data/database-queues/database-queues-delete-mutation.ts index f11846e102c31..4edf1913669a8 100644 --- a/apps/studio/data/database-queues/database-queues-delete-mutation.ts +++ b/apps/studio/data/database-queues/database-queues-delete-mutation.ts @@ -38,22 +38,20 @@ export const useDatabaseQueueDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteDatabaseQueue(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(databaseQueuesKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete database queue: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteDatabaseQueue(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(databaseQueuesKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete database queue: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-queues/database-queues-expose-postgrest-status-query.ts b/apps/studio/data/database-queues/database-queues-expose-postgrest-status-query.ts index ea95acfd5ba11..b298b7290ea78 100644 --- a/apps/studio/data/database-queues/database-queues-expose-postgrest-status-query.ts +++ b/apps/studio/data/database-queues/database-queues-expose-postgrest-status-query.ts @@ -37,11 +37,9 @@ export const useQueuesExposePostgrestStatusQuery = ( { projectRef, connectionString }: DatabaseQueuesVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - databaseQueuesKeys.exposePostgrestStatus(projectRef), - () => getDatabaseQueuesExposePostgrestStatus({ projectRef, connectionString }), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseQueuesKeys.exposePostgrestStatus(projectRef), + queryFn: () => getDatabaseQueuesExposePostgrestStatus({ projectRef, connectionString }), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database-queues/database-queues-metrics-query.ts b/apps/studio/data/database-queues/database-queues-metrics-query.ts index 5741d44f6c6ac..21bee875c3658 100644 --- a/apps/studio/data/database-queues/database-queues-metrics-query.ts +++ b/apps/studio/data/database-queues/database-queues-metrics-query.ts @@ -79,11 +79,9 @@ export const useQueuesMetricsQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databaseQueuesKeys.metrics(projectRef, queueName), - () => getDatabaseQueuesMetrics({ projectRef, connectionString, queueName }), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseQueuesKeys.metrics(projectRef, queueName), + queryFn: () => getDatabaseQueuesMetrics({ projectRef, connectionString, queueName }), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database-queues/database-queues-purge-mutation.ts b/apps/studio/data/database-queues/database-queues-purge-mutation.ts index 91f66ceb50b70..a5f6c2389b4e2 100644 --- a/apps/studio/data/database-queues/database-queues-purge-mutation.ts +++ b/apps/studio/data/database-queues/database-queues-purge-mutation.ts @@ -38,24 +38,22 @@ export const useDatabaseQueuePurgeMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => purgeDatabaseQueue(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, queueName } = variables - await queryClient.invalidateQueries( - databaseQueuesKeys.getMessagesInfinite(projectRef, queueName) - ) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to purge database queue: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => purgeDatabaseQueue(vars), + async onSuccess(data, variables, context) { + const { projectRef, queueName } = variables + await queryClient.invalidateQueries( + databaseQueuesKeys.getMessagesInfinite(projectRef, queueName) + ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to purge database queue: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-queues/database-queues-query.ts b/apps/studio/data/database-queues/database-queues-query.ts index e32ed69bcab13..9726507f7da7a 100644 --- a/apps/studio/data/database-queues/database-queues-query.ts +++ b/apps/studio/data/database-queues/database-queues-query.ts @@ -35,11 +35,9 @@ export const useQueuesQuery = ( { projectRef, connectionString }: DatabaseQueuesVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - databaseQueuesKeys.list(projectRef), - () => getDatabaseQueues({ projectRef, connectionString }), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseQueuesKeys.list(projectRef), + queryFn: () => getDatabaseQueues({ projectRef, connectionString }), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database-queues/database-queues-toggle-postgrest-mutation.ts b/apps/studio/data/database-queues/database-queues-toggle-postgrest-mutation.ts index 6c54894920fa0..39e21f75727d3 100644 --- a/apps/studio/data/database-queues/database-queues-toggle-postgrest-mutation.ts +++ b/apps/studio/data/database-queues/database-queues-toggle-postgrest-mutation.ts @@ -254,7 +254,8 @@ export const useDatabaseQueueToggleExposeMutation = ({ DatabaseQueueExposePostgrestData, ResponseError, DatabaseQueueExposePostgrestVariables - >((vars) => toggleQueuesExposurePostgrest(vars), { + >({ + mutationFn: (vars) => toggleQueuesExposurePostgrest(vars), async onSuccess(data, variables, context) { const { projectRef } = variables await queryClient.invalidateQueries(databaseQueuesKeys.exposePostgrestStatus(projectRef)) diff --git a/apps/studio/data/database-roles/database-role-create-mutation.ts b/apps/studio/data/database-roles/database-role-create-mutation.ts index 49f5b03467cb0..2b45a6674ac22 100644 --- a/apps/studio/data/database-roles/database-role-create-mutation.ts +++ b/apps/studio/data/database-roles/database-role-create-mutation.ts @@ -41,22 +41,20 @@ export const useDatabaseRoleCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createDatabaseRole(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await invalidateRolesQuery(queryClient, projectRef) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create database role: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createDatabaseRole(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await invalidateRolesQuery(queryClient, projectRef) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create database role: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-roles/database-role-delete-mutation.ts b/apps/studio/data/database-roles/database-role-delete-mutation.ts index acd97adac7f0a..2dbc00f29be06 100644 --- a/apps/studio/data/database-roles/database-role-delete-mutation.ts +++ b/apps/studio/data/database-roles/database-role-delete-mutation.ts @@ -43,22 +43,20 @@ export const useDatabaseRoleDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteDatabaseRole(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await invalidateRolesQuery(queryClient, projectRef) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete database role: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteDatabaseRole(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await invalidateRolesQuery(queryClient, projectRef) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete database role: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-roles/database-role-update-mutation.ts b/apps/studio/data/database-roles/database-role-update-mutation.ts index d12cf0d716bfb..a3cadbd917fcd 100644 --- a/apps/studio/data/database-roles/database-role-update-mutation.ts +++ b/apps/studio/data/database-roles/database-role-update-mutation.ts @@ -43,22 +43,20 @@ export const useDatabaseRoleUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateDatabaseRole(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await invalidateRolesQuery(queryClient, projectRef) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update database role: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateDatabaseRole(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await invalidateRolesQuery(queryClient, projectRef) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update database role: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-roles/database-roles-query.ts b/apps/studio/data/database-roles/database-roles-query.ts index 6b31844ff51d9..c87a7c47e54dd 100644 --- a/apps/studio/data/database-roles/database-roles-query.ts +++ b/apps/studio/data/database-roles/database-roles-query.ts @@ -33,14 +33,12 @@ export const useDatabaseRolesQuery = ( { projectRef, connectionString }: DatabaseRolesVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - databaseRoleKeys.databaseRoles(projectRef), - ({ signal }) => getDatabaseRoles({ projectRef, connectionString }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseRoleKeys.databaseRoles(projectRef), + queryFn: ({ signal }) => getDatabaseRoles({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) export function invalidateRolesQuery(client: QueryClient, projectRef: string | undefined) { return client.invalidateQueries(databaseRoleKeys.databaseRoles(projectRef)) diff --git a/apps/studio/data/database-triggers/database-trigger-create-mutation.ts b/apps/studio/data/database-triggers/database-trigger-create-mutation.ts index d9e4e74523ced..b74bf73fc3917 100644 --- a/apps/studio/data/database-triggers/database-trigger-create-mutation.ts +++ b/apps/studio/data/database-triggers/database-trigger-create-mutation.ts @@ -41,22 +41,20 @@ export const useDatabaseTriggerCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createDatabaseTrigger(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(databaseTriggerKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create database trigger: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createDatabaseTrigger(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(databaseTriggerKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create database trigger: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-triggers/database-trigger-delete-mutation.ts b/apps/studio/data/database-triggers/database-trigger-delete-mutation.ts index 02d88c156063a..e1706df661fbf 100644 --- a/apps/studio/data/database-triggers/database-trigger-delete-mutation.ts +++ b/apps/studio/data/database-triggers/database-trigger-delete-mutation.ts @@ -46,22 +46,20 @@ export const useDatabaseTriggerDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteDatabaseTrigger(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(databaseTriggerKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete database trigger: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteDatabaseTrigger(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(databaseTriggerKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete database trigger: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-triggers/database-trigger-update-mutation.ts b/apps/studio/data/database-triggers/database-trigger-update-mutation.ts index 1c0c8d62f26f6..a57221377d5d8 100644 --- a/apps/studio/data/database-triggers/database-trigger-update-mutation.ts +++ b/apps/studio/data/database-triggers/database-trigger-update-mutation.ts @@ -48,22 +48,20 @@ export const useDatabaseTriggerUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateDatabaseTrigger(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(databaseTriggerKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update database trigger: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateDatabaseTrigger(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(databaseTriggerKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update database trigger: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-triggers/database-trigger-update-transaction-mutation.ts b/apps/studio/data/database-triggers/database-trigger-update-transaction-mutation.ts index a010202a23d7f..42c55ad7f8f72 100644 --- a/apps/studio/data/database-triggers/database-trigger-update-transaction-mutation.ts +++ b/apps/studio/data/database-triggers/database-trigger-update-transaction-mutation.ts @@ -63,22 +63,20 @@ export const useDatabaseTriggerUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateDatabaseTrigger(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(databaseTriggerKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update database trigger: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateDatabaseTrigger(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(databaseTriggerKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update database trigger: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database-triggers/database-triggers-query.ts b/apps/studio/data/database-triggers/database-triggers-query.ts index 5b80cc9fc3ec2..4e3c9a60a38f5 100644 --- a/apps/studio/data/database-triggers/database-triggers-query.ts +++ b/apps/studio/data/database-triggers/database-triggers-query.ts @@ -45,22 +45,20 @@ export const useDatabaseHooksQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databaseTriggerKeys.list(projectRef), - ({ signal }) => getDatabaseTriggers({ projectRef, connectionString }, signal), - { - select: (data) => { - return data.filter((trigger) => { - return ( - trigger.function_schema === 'supabase_functions' && - (trigger.schema !== 'net' || trigger.function_args.length === 0) - ) - }) as any - }, - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseTriggerKeys.list(projectRef), + queryFn: ({ signal }) => getDatabaseTriggers({ projectRef, connectionString }, signal), + select: (data) => { + return data.filter((trigger) => { + return ( + trigger.function_schema === 'supabase_functions' && + (trigger.schema !== 'net' || trigger.function_args.length === 0) + ) + }) as any + }, + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) export const useDatabaseTriggersQuery = ( { projectRef, connectionString }: DatabaseTriggersVariables, @@ -69,11 +67,9 @@ export const useDatabaseTriggersQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databaseTriggerKeys.list(projectRef), - ({ signal }) => getDatabaseTriggers({ projectRef, connectionString }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseTriggerKeys.list(projectRef), + queryFn: ({ signal }) => getDatabaseTriggers({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database/backup-download-mutation.ts b/apps/studio/data/database/backup-download-mutation.ts index a6460101c3da1..3a1915bf29b3d 100644 --- a/apps/studio/data/database/backup-download-mutation.ts +++ b/apps/studio/data/database/backup-download-mutation.ts @@ -31,20 +31,18 @@ export const useBackupDownloadMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => downloadBackup(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to download backup: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => downloadBackup(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to download backup: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database/backup-query.ts b/apps/studio/data/database/backup-query.ts index b4f6430dfa6f6..4f11dbd2f5276 100644 --- a/apps/studio/data/database/backup-query.ts +++ b/apps/studio/data/database/backup-query.ts @@ -33,8 +33,9 @@ export const useDownloadableBackupQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.backups(projectRef), - ({ signal }) => getDownloadableBackup({ projectRef }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: databaseKeys.backups(projectRef), + queryFn: ({ signal }) => getDownloadableBackup({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database/backup-restore-mutation.ts b/apps/studio/data/database/backup-restore-mutation.ts index 615246a4fa15a..142cef5707122 100644 --- a/apps/studio/data/database/backup-restore-mutation.ts +++ b/apps/studio/data/database/backup-restore-mutation.ts @@ -41,20 +41,18 @@ export const useBackupRestoreMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => restoreFromBackup(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to restore from backup: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => restoreFromBackup(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to restore from backup: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database/backups-query.ts b/apps/studio/data/database/backups-query.ts index 7cef5a9462a66..6767055fd8cfc 100644 --- a/apps/studio/data/database/backups-query.ts +++ b/apps/studio/data/database/backups-query.ts @@ -34,12 +34,10 @@ export const useBackupsQuery = ( // [Joshen] Check for specifically false to account for project not loaded yet const isOrioleDbInAws = useIsOrioleDbInAws() - return useQuery( - databaseKeys.backups(projectRef), - ({ signal }) => getBackups({ projectRef }, signal), - { - enabled: enabled && !isOrioleDbInAws && typeof projectRef !== 'undefined', - ...options, - } - ) + return useQuery({ + queryKey: databaseKeys.backups(projectRef), + queryFn: ({ signal }) => getBackups({ projectRef }, signal), + enabled: enabled && !isOrioleDbInAws && typeof projectRef !== 'undefined', + ...options, + }) } diff --git a/apps/studio/data/database/constraints-query.ts b/apps/studio/data/database/constraints-query.ts index ff111d7686b54..ae38e710f17dd 100644 --- a/apps/studio/data/database/constraints-query.ts +++ b/apps/studio/data/database/constraints-query.ts @@ -77,11 +77,9 @@ export const useTableConstraintsQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.tableConstraints(projectRef, id), - ({ signal }) => getTableConstraints({ projectRef, connectionString, id }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.tableConstraints(projectRef, id), + queryFn: ({ signal }) => getTableConstraints({ projectRef, connectionString, id }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database/database-password-reset-mutation.ts b/apps/studio/data/database/database-password-reset-mutation.ts index ad139d8087c3e..60b4b8116e358 100644 --- a/apps/studio/data/database/database-password-reset-mutation.ts +++ b/apps/studio/data/database/database-password-reset-mutation.ts @@ -34,22 +34,20 @@ export const useDatabasePasswordResetMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => resetDatabasePassword(vars), - { - async onSuccess(data, variables, context) { - await queryClient.invalidateQueries(projectKeys.detail(variables.ref)) - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to reset database password: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => resetDatabasePassword(vars), + async onSuccess(data, variables, context) { + await queryClient.invalidateQueries(projectKeys.detail(variables.ref)) + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to reset database password: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database/database-size-query.ts b/apps/studio/data/database/database-size-query.ts index c5fcdaf2626ba..12690c11bb4bf 100644 --- a/apps/studio/data/database/database-size-query.ts +++ b/apps/studio/data/database/database-size-query.ts @@ -46,11 +46,9 @@ export const useDatabaseSizeQuery = ( { projectRef, connectionString }: DatabaseSizeVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.databaseSize(projectRef), - ({ signal }) => getDatabaseSize({ projectRef, connectionString }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.databaseSize(projectRef), + queryFn: ({ signal }) => getDatabaseSize({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database/enable-physical-backups-mutation.ts b/apps/studio/data/database/enable-physical-backups-mutation.ts index 3ce9b937ce528..2a89ffd12f146 100644 --- a/apps/studio/data/database/enable-physical-backups-mutation.ts +++ b/apps/studio/data/database/enable-physical-backups-mutation.ts @@ -26,20 +26,18 @@ export const useEnablePhysicalBackupsMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => enablePhysicalBackups(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to enable physical backups: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => enablePhysicalBackups(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to enable physical backups: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database/entity-definitions-query.ts b/apps/studio/data/database/entity-definitions-query.ts index 3cbea18a8a804..3630ba2e578da 100644 --- a/apps/studio/data/database/entity-definitions-query.ts +++ b/apps/studio/data/database/entity-definitions-query.ts @@ -111,11 +111,10 @@ export const useEntityDefinitionsQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.entityDefinitions(projectRef, schemas), - ({ signal }) => getEntityDefinitions({ projectRef, connectionString, schemas, limit }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && schemas.length > 0, - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.entityDefinitions(projectRef, schemas), + queryFn: ({ signal }) => + getEntityDefinitions({ projectRef, connectionString, schemas, limit }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && schemas.length > 0, + ...options, + }) diff --git a/apps/studio/data/database/foreign-key-constraints-query.ts b/apps/studio/data/database/foreign-key-constraints-query.ts index 6774b7a873083..12b39230ebd3a 100644 --- a/apps/studio/data/database/foreign-key-constraints-query.ts +++ b/apps/studio/data/database/foreign-key-constraints-query.ts @@ -134,14 +134,13 @@ export const useForeignKeyConstraintsQuery = ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.foreignKeyConstraints(projectRef, schema), - ({ signal }) => getForeignKeyConstraints({ projectRef, connectionString, schema }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof schema !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.foreignKeyConstraints(projectRef, schema), + queryFn: ({ signal }) => + getForeignKeyConstraints({ projectRef, connectionString, schema }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && typeof schema !== 'undefined', + ...options, + }) export function prefetchForeignKeyConstraints( client: QueryClient, diff --git a/apps/studio/data/database/hooks-enable-mutation.ts b/apps/studio/data/database/hooks-enable-mutation.ts index b3b0dbee867d9..6a98f02c27ec6 100644 --- a/apps/studio/data/database/hooks-enable-mutation.ts +++ b/apps/studio/data/database/hooks-enable-mutation.ts @@ -28,22 +28,20 @@ export const useHooksEnableMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => enableDatabaseWebhooks(vars), - { - async onSuccess(data, variables, context) { - const { ref } = variables - await onSuccess?.(data, variables, context) - await invalidateSchemasQuery(queryClient, ref) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to enable webhooks: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => enableDatabaseWebhooks(vars), + async onSuccess(data, variables, context) { + const { ref } = variables + await onSuccess?.(data, variables, context) + await invalidateSchemasQuery(queryClient, ref) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to enable webhooks: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database/keywords-query.ts b/apps/studio/data/database/keywords-query.ts index 2369dd86c06fd..28ba8b8d1f975 100644 --- a/apps/studio/data/database/keywords-query.ts +++ b/apps/studio/data/database/keywords-query.ts @@ -36,11 +36,9 @@ export const useKeywordsQuery = ( { projectRef, connectionString }: KeywordsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.keywords(projectRef), - ({ signal }) => getKeywords({ projectRef, connectionString }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.keywords(projectRef), + queryFn: ({ signal }) => getKeywords({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database/max-connections-query.ts b/apps/studio/data/database/max-connections-query.ts index 353ab0d73b846..8103c8d55655e 100644 --- a/apps/studio/data/database/max-connections-query.ts +++ b/apps/studio/data/database/max-connections-query.ts @@ -41,11 +41,9 @@ export const useMaxConnectionsQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.maxConnections(projectRef), - ({ signal }) => getMaxConnections({ projectRef, connectionString }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.maxConnections(projectRef), + queryFn: ({ signal }) => getMaxConnections({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database/migration-upsert-mutation.ts b/apps/studio/data/database/migration-upsert-mutation.ts index 2dea72dfefd6f..8bd541e1b3ac7 100644 --- a/apps/studio/data/database/migration-upsert-mutation.ts +++ b/apps/studio/data/database/migration-upsert-mutation.ts @@ -49,22 +49,20 @@ export const useMigrationUpsertMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => upsertMigration(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(databaseKeys.migrations(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to upsert migration: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => upsertMigration(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(databaseKeys.migrations(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to upsert migration: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database/migrations-query.ts b/apps/studio/data/database/migrations-query.ts index 41801877ca826..ca47a1296a4ee 100644 --- a/apps/studio/data/database/migrations-query.ts +++ b/apps/studio/data/database/migrations-query.ts @@ -57,11 +57,9 @@ export const useMigrationsQuery = ( { projectRef, connectionString }: MigrationsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.migrations(projectRef), - ({ signal }) => getMigrations({ projectRef, connectionString }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.migrations(projectRef), + queryFn: ({ signal }) => getMigrations({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database/pgbouncer-config-query.ts b/apps/studio/data/database/pgbouncer-config-query.ts index 71df7be13d052..4bbd2f5a35616 100644 --- a/apps/studio/data/database/pgbouncer-config-query.ts +++ b/apps/studio/data/database/pgbouncer-config-query.ts @@ -33,11 +33,9 @@ export const usePgbouncerConfigQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.pgbouncerConfig(projectRef), - ({ signal }) => getPgbouncerConfig({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && IS_PLATFORM, - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.pgbouncerConfig(projectRef), + queryFn: ({ signal }) => getPgbouncerConfig({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && IS_PLATFORM, + ...options, + }) diff --git a/apps/studio/data/database/pgbouncer-config-update-mutation.ts b/apps/studio/data/database/pgbouncer-config-update-mutation.ts index 0fe0f4819ad29..603feae87f2a7 100644 --- a/apps/studio/data/database/pgbouncer-config-update-mutation.ts +++ b/apps/studio/data/database/pgbouncer-config-update-mutation.ts @@ -54,7 +54,8 @@ export const usePgbouncerConfigurationUpdateMutation = ({ PgbouncerConfigurationUpdateData, ResponseError, PgbouncerConfigurationUpdateVariables - >((vars) => updatePgbouncerConfiguration(vars), { + >({ + mutationFn: (vars) => updatePgbouncerConfiguration(vars), async onSuccess(data, variables, context) { const { ref } = variables await queryClient.invalidateQueries(databaseKeys.pgbouncerConfig(ref)) diff --git a/apps/studio/data/database/pgbouncer-status-query.ts b/apps/studio/data/database/pgbouncer-status-query.ts index fd178fd8eb222..8a89625005781 100644 --- a/apps/studio/data/database/pgbouncer-status-query.ts +++ b/apps/studio/data/database/pgbouncer-status-query.ts @@ -32,11 +32,9 @@ export const usePgbouncerStatusQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.pgbouncerStatus(projectRef), - ({ signal }) => getPgbouncerStatus({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.pgbouncerStatus(projectRef), + queryFn: ({ signal }) => getPgbouncerStatus({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database/pitr-restore-mutation.ts b/apps/studio/data/database/pitr-restore-mutation.ts index 1b06f73cafa9a..26c102e77dc66 100644 --- a/apps/studio/data/database/pitr-restore-mutation.ts +++ b/apps/studio/data/database/pitr-restore-mutation.ts @@ -28,20 +28,18 @@ export const usePitrRestoreMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => restoreFromPitr(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to start PITR restoration: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => restoreFromPitr(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to start PITR restoration: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database/primary-keys-exists-query.ts b/apps/studio/data/database/primary-keys-exists-query.ts index af72d7d61a146..3074b36464684 100644 --- a/apps/studio/data/database/primary-keys-exists-query.ts +++ b/apps/studio/data/database/primary-keys-exists-query.ts @@ -46,12 +46,10 @@ export const useCheckPrimaryKeysExists = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.checkPrimaryKeysExists(projectRef, tables), - () => checkPrimaryKeysExists({ projectRef, connectionString, tables }), - { - retry: false, - enabled: enabled && typeof projectRef !== 'undefined' && tables.length > 0, - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.checkPrimaryKeysExists(projectRef, tables), + queryFn: () => checkPrimaryKeysExists({ projectRef, connectionString, tables }), + retry: false, + enabled: enabled && typeof projectRef !== 'undefined' && tables.length > 0, + ...options, + }) diff --git a/apps/studio/data/database/retrieve-index-advisor-result-query.ts b/apps/studio/data/database/retrieve-index-advisor-result-query.ts index 5b16973c6edd4..fcb97c9b032ea 100644 --- a/apps/studio/data/database/retrieve-index-advisor-result-query.ts +++ b/apps/studio/data/database/retrieve-index-advisor-result-query.ts @@ -47,17 +47,15 @@ export const useGetIndexAdvisorResult = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.indexAdvisorFromQuery(projectRef, query), - () => getIndexAdvisorResult({ projectRef, connectionString, query }), - { - retry: false, - enabled: - (enabled && - typeof projectRef !== 'undefined' && - typeof query !== 'undefined' && - (query.startsWith('select') || query.startsWith('SELECT'))) || - query.trim().toLowerCase().startsWith('with pgrst_source'), - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.indexAdvisorFromQuery(projectRef, query), + queryFn: () => getIndexAdvisorResult({ projectRef, connectionString, query }), + retry: false, + enabled: + (enabled && + typeof projectRef !== 'undefined' && + typeof query !== 'undefined' && + (query.startsWith('select') || query.startsWith('SELECT'))) || + query.trim().toLowerCase().startsWith('with pgrst_source'), + ...options, + }) diff --git a/apps/studio/data/database/retrieve-index-from-select-query.ts b/apps/studio/data/database/retrieve-index-from-select-query.ts index 24505fd137f92..493571532e883 100644 --- a/apps/studio/data/database/retrieve-index-from-select-query.ts +++ b/apps/studio/data/database/retrieve-index-from-select-query.ts @@ -149,19 +149,17 @@ export const useGetIndexesFromSelectQuery = ( - databaseKeys.indexesFromQuery(projectRef, query), - () => getInvolvedIndexesInSelectQuery({ projectRef, connectionString, query }), - { - retry: false, - enabled: - enabled && - typeof projectRef !== 'undefined' && - typeof query !== 'undefined' && - isValidQueryForIndexing, - ...options, - } - ) + >({ + queryKey: databaseKeys.indexesFromQuery(projectRef, query), + queryFn: () => getInvolvedIndexesInSelectQuery({ projectRef, connectionString, query }), + retry: false, + enabled: + enabled && + typeof projectRef !== 'undefined' && + typeof query !== 'undefined' && + isValidQueryForIndexing, + ...options, + }) } // Helper functions diff --git a/apps/studio/data/database/schema-create-mutation.ts b/apps/studio/data/database/schema-create-mutation.ts index 47e22402b2e0a..258956504dc16 100644 --- a/apps/studio/data/database/schema-create-mutation.ts +++ b/apps/studio/data/database/schema-create-mutation.ts @@ -34,22 +34,20 @@ export const useSchemaCreateMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createSchema(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await invalidateSchemasQuery(queryClient, projectRef) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create schema: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createSchema(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await invalidateSchemasQuery(queryClient, projectRef) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create schema: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/database/schemas-query.ts b/apps/studio/data/database/schemas-query.ts index 5bbc44ae46139..9e52ea2067830 100644 --- a/apps/studio/data/database/schemas-query.ts +++ b/apps/studio/data/database/schemas-query.ts @@ -38,14 +38,12 @@ export const useSchemasQuery = ( { projectRef, connectionString }: SchemasVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.schemas(projectRef), - ({ signal }) => getSchemas({ projectRef, connectionString }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.schemas(projectRef), + queryFn: ({ signal }) => getSchemas({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) export function invalidateSchemasQuery(client: QueryClient, projectRef: string | undefined) { return client.invalidateQueries(databaseKeys.schemas(projectRef)) diff --git a/apps/studio/data/database/supavisor-configuration-query.ts b/apps/studio/data/database/supavisor-configuration-query.ts index 59e4237fd81a2..599630d5875db 100644 --- a/apps/studio/data/database/supavisor-configuration-query.ts +++ b/apps/studio/data/database/supavisor-configuration-query.ts @@ -33,11 +33,9 @@ export const useSupavisorConfigurationQuery = = {} ) => - useQuery( - databaseKeys.poolingConfiguration(projectRef), - ({ signal }) => getSupavisorConfiguration({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && IS_PLATFORM, - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.poolingConfiguration(projectRef), + queryFn: ({ signal }) => getSupavisorConfiguration({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && IS_PLATFORM, + ...options, + }) diff --git a/apps/studio/data/database/supavisor-configuration-update-mutation.ts b/apps/studio/data/database/supavisor-configuration-update-mutation.ts index d09d42c36bc8d..5179822e3aca4 100644 --- a/apps/studio/data/database/supavisor-configuration-update-mutation.ts +++ b/apps/studio/data/database/supavisor-configuration-update-mutation.ts @@ -45,7 +45,8 @@ export const useSupavisorConfigurationUpdateMutation = ({ SupavisorConfigurationUpdateData, ResponseError, SupavisorConfigurationUpdateVariables - >((vars) => updateSupavisorConfiguration(vars), { + >({ + mutationFn: (vars) => updateSupavisorConfiguration(vars), async onSuccess(data, variables, context) { const { ref } = variables await queryClient.invalidateQueries(databaseKeys.poolingConfiguration(ref)) diff --git a/apps/studio/data/database/table-columns-query.ts b/apps/studio/data/database/table-columns-query.ts index e7038a5787a99..45b72804d6895 100644 --- a/apps/studio/data/database/table-columns-query.ts +++ b/apps/studio/data/database/table-columns-query.ts @@ -113,11 +113,10 @@ export const useTableColumnsQuery = ( { projectRef, connectionString, schema, table }: TableColumnsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.tableColumns(projectRef, schema, table), - ({ signal }) => getTableColumns({ projectRef, connectionString, schema, table }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.tableColumns(projectRef, schema, table), + queryFn: ({ signal }) => + getTableColumns({ projectRef, connectionString, schema, table }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/database/table-definition-query.ts b/apps/studio/data/database/table-definition-query.ts index f912902e23063..b5b5bb1593b1b 100644 --- a/apps/studio/data/database/table-definition-query.ts +++ b/apps/studio/data/database/table-definition-query.ts @@ -70,12 +70,10 @@ export const useTableDefinitionQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.tableDefinition(projectRef, id), - ({ signal }) => getTableDefinition({ projectRef, connectionString, id }, signal), - { - enabled: - enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined' && !isNaN(id), - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.tableDefinition(projectRef, id), + queryFn: ({ signal }) => getTableDefinition({ projectRef, connectionString, id }, signal), + enabled: + enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined' && !isNaN(id), + ...options, + }) diff --git a/apps/studio/data/database/view-definition-query.ts b/apps/studio/data/database/view-definition-query.ts index 99a3511d0d748..fbd2f1b3cd202 100644 --- a/apps/studio/data/database/view-definition-query.ts +++ b/apps/studio/data/database/view-definition-query.ts @@ -62,12 +62,10 @@ export const useViewDefinitionQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - databaseKeys.viewDefinition(projectRef, id), - ({ signal }) => getViewDefinition({ projectRef, connectionString, id }, signal), - { - enabled: - enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined' && !isNaN(id), - ...options, - } - ) + useQuery({ + queryKey: databaseKeys.viewDefinition(projectRef, id), + queryFn: ({ signal }) => getViewDefinition({ projectRef, connectionString, id }, signal), + enabled: + enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined' && !isNaN(id), + ...options, + }) diff --git a/apps/studio/data/docs/project-json-schema-query.ts b/apps/studio/data/docs/project-json-schema-query.ts index 54aeae44a1b1a..1d55dc64b32be 100644 --- a/apps/studio/data/docs/project-json-schema-query.ts +++ b/apps/studio/data/docs/project-json-schema-query.ts @@ -95,11 +95,9 @@ export const useProjectJsonSchemaQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - docsKeys.jsonSchema(projectRef), - ({ signal }) => getProjectJsonSchema({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: docsKeys.jsonSchema(projectRef), + queryFn: ({ signal }) => getProjectJsonSchema({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/documents/document-query.ts b/apps/studio/data/documents/document-query.ts index 05dfee7cf7a75..c10fa93b85271 100644 --- a/apps/studio/data/documents/document-query.ts +++ b/apps/studio/data/documents/document-query.ts @@ -47,11 +47,9 @@ export const useDocumentQuery = ( { orgSlug, docType }: DocumentVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - documentKeys.resource(orgSlug, docType), - ({ signal }) => getDocument({ orgSlug, docType }, signal), - { - enabled: enabled && typeof orgSlug !== 'undefined' && typeof docType !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: documentKeys.resource(orgSlug, docType), + queryFn: ({ signal }) => getDocument({ orgSlug, docType }, signal), + enabled: enabled && typeof orgSlug !== 'undefined' && typeof docType !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/documents/dpa-request-mutation.ts b/apps/studio/data/documents/dpa-request-mutation.ts index 486a5c420353e..1137a6b6bc3ff 100644 --- a/apps/studio/data/documents/dpa-request-mutation.ts +++ b/apps/studio/data/documents/dpa-request-mutation.ts @@ -28,20 +28,18 @@ export const useDpaRequestMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => requestDpa(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to request DPA: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => requestDpa(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to request DPA: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/edge-functions/edge-function-body-query.ts b/apps/studio/data/edge-functions/edge-function-body-query.ts index ddd91121faf59..2f9b921ad2e14 100644 --- a/apps/studio/data/edge-functions/edge-function-body-query.ts +++ b/apps/studio/data/edge-functions/edge-function-body-query.ts @@ -73,12 +73,10 @@ export const useEdgeFunctionBodyQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - edgeFunctionsKeys.body(projectRef, slug), - ({ signal }) => getEdgeFunctionBody({ projectRef, slug }, signal), - { - enabled: - IS_PLATFORM && enabled && typeof projectRef !== 'undefined' && typeof slug !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: edgeFunctionsKeys.body(projectRef, slug), + queryFn: ({ signal }) => getEdgeFunctionBody({ projectRef, slug }, signal), + enabled: + IS_PLATFORM && enabled && typeof projectRef !== 'undefined' && typeof slug !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/edge-functions/edge-function-query.ts b/apps/studio/data/edge-functions/edge-function-query.ts index c8d14919498f6..4625fcf86f50f 100644 --- a/apps/studio/data/edge-functions/edge-function-query.ts +++ b/apps/studio/data/edge-functions/edge-function-query.ts @@ -35,12 +35,10 @@ export const useEdgeFunctionQuery = ( { projectRef, slug }: EdgeFunctionVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - edgeFunctionsKeys.detail(projectRef, slug), - ({ signal }) => getEdgeFunction({ projectRef, slug }, signal), - { - enabled: - IS_PLATFORM && enabled && typeof projectRef !== 'undefined' && typeof slug !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: edgeFunctionsKeys.detail(projectRef, slug), + queryFn: ({ signal }) => getEdgeFunction({ projectRef, slug }, signal), + enabled: + IS_PLATFORM && enabled && typeof projectRef !== 'undefined' && typeof slug !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/edge-functions/edge-function-test-mutation.ts b/apps/studio/data/edge-functions/edge-function-test-mutation.ts index 1b0b202b8c238..ab2df63c87316 100644 --- a/apps/studio/data/edge-functions/edge-function-test-mutation.ts +++ b/apps/studio/data/edge-functions/edge-function-test-mutation.ts @@ -52,20 +52,18 @@ export const useEdgeFunctionTestMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => testEdgeFunction(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to test edge function: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => testEdgeFunction(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to test edge function: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/edge-functions/edge-functions-delete-mutation.ts b/apps/studio/data/edge-functions/edge-functions-delete-mutation.ts index e6aab7c26c924..c575d7dbcd7af 100644 --- a/apps/studio/data/edge-functions/edge-functions-delete-mutation.ts +++ b/apps/studio/data/edge-functions/edge-functions-delete-mutation.ts @@ -35,24 +35,22 @@ export const useEdgeFunctionDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteEdgeFunction(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(edgeFunctionsKeys.list(projectRef), { - refetchType: 'all', - }) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete edge function: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteEdgeFunction(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(edgeFunctionsKeys.list(projectRef), { + refetchType: 'all', + }) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete edge function: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/edge-functions/edge-functions-deploy-mutation.ts b/apps/studio/data/edge-functions/edge-functions-deploy-mutation.ts index 7d5a05e7e4669..fa00cb4f9e71e 100644 --- a/apps/studio/data/edge-functions/edge-functions-deploy-mutation.ts +++ b/apps/studio/data/edge-functions/edge-functions-deploy-mutation.ts @@ -58,25 +58,24 @@ export const useEdgeFunctionDeployMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deployEdgeFunction(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, slug } = variables - await Promise.all([ - queryClient.invalidateQueries(edgeFunctionsKeys.detail(projectRef, slug)), - queryClient.invalidateQueries(edgeFunctionsKeys.body(projectRef, slug)), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to deploy edge function: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deployEdgeFunction(vars), + async onSuccess(data, variables, context) { + const { projectRef, slug } = variables + await Promise.all([ + queryClient.invalidateQueries(edgeFunctionsKeys.list(projectRef)), + queryClient.invalidateQueries(edgeFunctionsKeys.detail(projectRef, slug)), + queryClient.invalidateQueries(edgeFunctionsKeys.body(projectRef, slug)), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to deploy edge function: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/edge-functions/edge-functions-query.ts b/apps/studio/data/edge-functions/edge-functions-query.ts index 3df3688111e55..4b872cf0209aa 100644 --- a/apps/studio/data/edge-functions/edge-functions-query.ts +++ b/apps/studio/data/edge-functions/edge-functions-query.ts @@ -31,8 +31,9 @@ export const useEdgeFunctionsQuery = ( { projectRef }: EdgeFunctionsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - edgeFunctionsKeys.list(projectRef), - ({ signal }) => getEdgeFunctions({ projectRef }, signal), - { enabled: IS_PLATFORM && enabled && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: edgeFunctionsKeys.list(projectRef), + queryFn: ({ signal }) => getEdgeFunctions({ projectRef }, signal), + enabled: IS_PLATFORM && enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/edge-functions/edge-functions-update-mutation.ts b/apps/studio/data/edge-functions/edge-functions-update-mutation.ts index 1d9e501d79d98..5962c93ef2f9e 100644 --- a/apps/studio/data/edge-functions/edge-functions-update-mutation.ts +++ b/apps/studio/data/edge-functions/edge-functions-update-mutation.ts @@ -44,25 +44,23 @@ export const useEdgeFunctionUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateEdgeFunction(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, slug } = variables - await Promise.all([ - queryClient.invalidateQueries(edgeFunctionsKeys.detail(projectRef, slug)), - queryClient.invalidateQueries(edgeFunctionsKeys.list(projectRef)), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update edge function: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateEdgeFunction(vars), + async onSuccess(data, variables, context) { + const { projectRef, slug } = variables + await Promise.all([ + queryClient.invalidateQueries(edgeFunctionsKeys.detail(projectRef, slug)), + queryClient.invalidateQueries(edgeFunctionsKeys.list(projectRef)), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update edge function: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/entitlements/entitlements-query.ts b/apps/studio/data/entitlements/entitlements-query.ts index cf922714eaf56..c12b52f201e9b 100644 --- a/apps/studio/data/entitlements/entitlements-query.ts +++ b/apps/studio/data/entitlements/entitlements-query.ts @@ -30,9 +30,11 @@ export const useEntitlementsQuery = ( { slug }: EntitlementsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => { - return useQuery( - ['entitlements', slug], - ({ signal }) => getEntitlements({ slug }, signal), - { enabled: enabled && typeof slug !== 'undefined', ...options, staleTime: 1 * 60 * 1000 } - ) + return useQuery({ + queryKey: ['entitlements', slug], + queryFn: ({ signal }) => getEntitlements({ slug }, signal), + enabled: enabled && typeof slug !== 'undefined', + ...options, + staleTime: 1 * 60 * 1000, + }) } diff --git a/apps/studio/data/enumerated-types/enumerated-type-create-mutation.ts b/apps/studio/data/enumerated-types/enumerated-type-create-mutation.ts index c213d3441d2b7..0d468544ce671 100644 --- a/apps/studio/data/enumerated-types/enumerated-type-create-mutation.ts +++ b/apps/studio/data/enumerated-types/enumerated-type-create-mutation.ts @@ -45,22 +45,20 @@ export const useEnumeratedTypeCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createEnumeratedType(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(enumeratedTypesKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create enumerated type: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createEnumeratedType(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(enumeratedTypesKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create enumerated type: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/enumerated-types/enumerated-type-delete-mutation.ts b/apps/studio/data/enumerated-types/enumerated-type-delete-mutation.ts index bba3c0f008b71..c36530d77493e 100644 --- a/apps/studio/data/enumerated-types/enumerated-type-delete-mutation.ts +++ b/apps/studio/data/enumerated-types/enumerated-type-delete-mutation.ts @@ -35,22 +35,20 @@ export const useEnumeratedTypeDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteEnumeratedType(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(enumeratedTypesKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create enumerated type: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteEnumeratedType(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(enumeratedTypesKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create enumerated type: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/enumerated-types/enumerated-type-update-mutation.ts b/apps/studio/data/enumerated-types/enumerated-type-update-mutation.ts index 3aabaf9fab153..df73e2ef7fc46 100644 --- a/apps/studio/data/enumerated-types/enumerated-type-update-mutation.ts +++ b/apps/studio/data/enumerated-types/enumerated-type-update-mutation.ts @@ -71,22 +71,20 @@ export const useEnumeratedTypeUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateEnumeratedType(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(enumeratedTypesKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to add value to enumerated type: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateEnumeratedType(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(enumeratedTypesKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to add value to enumerated type: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/enumerated-types/enumerated-types-query.ts b/apps/studio/data/enumerated-types/enumerated-types-query.ts index ed61ae2291df8..6253eef547e6c 100644 --- a/apps/studio/data/enumerated-types/enumerated-types-query.ts +++ b/apps/studio/data/enumerated-types/enumerated-types-query.ts @@ -48,11 +48,9 @@ export const useEnumeratedTypesQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - enumeratedTypesKeys.list(projectRef), - ({ signal }) => getEnumeratedTypes({ projectRef, connectionString }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: enumeratedTypesKeys.list(projectRef), + queryFn: ({ signal }) => getEnumeratedTypes({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/fdw/fdw-create-mutation.ts b/apps/studio/data/fdw/fdw-create-mutation.ts index 4947c2b67ff3d..e8aabc120a17e 100644 --- a/apps/studio/data/fdw/fdw-create-mutation.ts +++ b/apps/studio/data/fdw/fdw-create-mutation.ts @@ -247,7 +247,8 @@ export const useFDWCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation((vars) => createFDW(vars), { + return useMutation({ + mutationFn: (vars) => createFDW(vars), async onSuccess(data, variables, context) { const { projectRef } = variables diff --git a/apps/studio/data/fdw/fdw-delete-mutation.ts b/apps/studio/data/fdw/fdw-delete-mutation.ts index 37cd3030c467c..25efcf5a5c288 100644 --- a/apps/studio/data/fdw/fdw-delete-mutation.ts +++ b/apps/studio/data/fdw/fdw-delete-mutation.ts @@ -104,7 +104,8 @@ export const useFDWDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation((vars) => deleteFDW(vars), { + return useMutation({ + mutationFn: (vars) => deleteFDW(vars), async onSuccess(data, variables, context) { const { projectRef } = variables diff --git a/apps/studio/data/fdw/fdw-import-foreign-schema-mutation.ts b/apps/studio/data/fdw/fdw-import-foreign-schema-mutation.ts index 81d257b57e461..472b0353c1796 100644 --- a/apps/studio/data/fdw/fdw-import-foreign-schema-mutation.ts +++ b/apps/studio/data/fdw/fdw-import-foreign-schema-mutation.ts @@ -50,29 +50,27 @@ export const useFDWImportForeignSchemaMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => importForeignSchema(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables + return useMutation({ + mutationFn: (vars) => importForeignSchema(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables - await Promise.all([ - queryClient.invalidateQueries(fdwKeys.list(projectRef), { refetchType: 'all' }), - queryClient.invalidateQueries(entityTypeKeys.list(projectRef)), - queryClient.invalidateQueries(foreignTableKeys.list(projectRef)), - queryClient.invalidateQueries(vaultSecretsKeys.list(projectRef)), - ]) + await Promise.all([ + queryClient.invalidateQueries(fdwKeys.list(projectRef), { refetchType: 'all' }), + queryClient.invalidateQueries(entityTypeKeys.list(projectRef)), + queryClient.invalidateQueries(foreignTableKeys.list(projectRef)), + queryClient.invalidateQueries(vaultSecretsKeys.list(projectRef)), + ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to import schema for foreign data wrapper: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to import schema for foreign data wrapper: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/fdw/fdw-update-mutation.ts b/apps/studio/data/fdw/fdw-update-mutation.ts index b079478ed8b1f..c07a5e7ebdc6a 100644 --- a/apps/studio/data/fdw/fdw-update-mutation.ts +++ b/apps/studio/data/fdw/fdw-update-mutation.ts @@ -74,7 +74,8 @@ export const useFDWUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation((vars) => updateFDW(vars), { + return useMutation({ + mutationFn: (vars) => updateFDW(vars), async onSuccess(data, variables, context) { const { projectRef } = variables diff --git a/apps/studio/data/fdw/fdws-query.ts b/apps/studio/data/fdw/fdws-query.ts index a4b4030d71cd3..da74ba15becf6 100644 --- a/apps/studio/data/fdw/fdws-query.ts +++ b/apps/studio/data/fdw/fdws-query.ts @@ -89,11 +89,9 @@ export const useFDWsQuery = ( { projectRef, connectionString }: FDWsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - fdwKeys.list(projectRef), - ({ signal }) => getFDWs({ projectRef, connectionString }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: fdwKeys.list(projectRef), + queryFn: ({ signal }) => getFDWs({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/feedback/exit-survey-send.ts b/apps/studio/data/feedback/exit-survey-send.ts index c8b8546c9b714..cfc9f884b1be1 100644 --- a/apps/studio/data/feedback/exit-survey-send.ts +++ b/apps/studio/data/feedback/exit-survey-send.ts @@ -41,17 +41,15 @@ export const useSendDowngradeFeedbackMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => sendDowngradeFeedback(vars), - { - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to submit exit survey: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => sendDowngradeFeedback(vars), + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to submit exit survey: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/feedback/feedback-category.ts b/apps/studio/data/feedback/feedback-category.ts index c0778f000228d..d683fc6eb03ff 100644 --- a/apps/studio/data/feedback/feedback-category.ts +++ b/apps/studio/data/feedback/feedback-category.ts @@ -49,11 +49,9 @@ export const useFeedbackCategoryQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - ['feedback-category', prompt], - ({ signal }) => getFeedbackCategory({ prompt }, signal), - { - enabled: enabled && !!prompt, - ...options, - } - ) + useQuery({ + queryKey: ['feedback-category', prompt], + queryFn: ({ signal }) => getFeedbackCategory({ prompt }, signal), + enabled: enabled && !!prompt, + ...options, + }) diff --git a/apps/studio/data/feedback/feedback-send.ts b/apps/studio/data/feedback/feedback-send.ts index 506a4f1f8011a..ede0f7c1423d7 100644 --- a/apps/studio/data/feedback/feedback-send.ts +++ b/apps/studio/data/feedback/feedback-send.ts @@ -40,17 +40,15 @@ export const useSendFeedbackMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => sendFeedback(vars), - { - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to submit feedback: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => sendFeedback(vars), + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to submit feedback: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/feedback/support-ticket-send.ts b/apps/studio/data/feedback/support-ticket-send.ts index 4dd9d102e770d..24a44f7f3d163 100644 --- a/apps/studio/data/feedback/support-ticket-send.ts +++ b/apps/studio/data/feedback/support-ticket-send.ts @@ -80,20 +80,18 @@ export const useSendSupportTicketMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => sendSupportTicket(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to submit support ticket: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => sendSupportTicket(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to submit support ticket: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/feedback/upgrade-survey-send.ts b/apps/studio/data/feedback/upgrade-survey-send.ts index 282bdcdf2587e..e87aff4bfc127 100644 --- a/apps/studio/data/feedback/upgrade-survey-send.ts +++ b/apps/studio/data/feedback/upgrade-survey-send.ts @@ -41,17 +41,15 @@ export const useSendUpgradeFeedbackMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => sendUpgradeFeedback(vars), - { - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to submit upgrade survey: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => sendUpgradeFeedback(vars), + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to submit upgrade survey: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/foreign-tables/foreign-tables-query.ts b/apps/studio/data/foreign-tables/foreign-tables-query.ts index bffbb857aaafd..cb6cfd90e9368 100644 --- a/apps/studio/data/foreign-tables/foreign-tables-query.ts +++ b/apps/studio/data/foreign-tables/foreign-tables-query.ts @@ -48,11 +48,11 @@ export const useForeignTablesQuery = ( { projectRef, connectionString, schema }: ForeignTablesVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - schema ? foreignTableKeys.listBySchema(projectRef, schema) : foreignTableKeys.list(projectRef), - ({ signal }) => getForeignTables({ projectRef, connectionString, schema }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: schema + ? foreignTableKeys.listBySchema(projectRef, schema) + : foreignTableKeys.list(projectRef), + queryFn: ({ signal }) => getForeignTables({ projectRef, connectionString, schema }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/integrations/aws-redirect-query.ts b/apps/studio/data/integrations/aws-redirect-query.ts index e9a030cb258f2..36699c47bff40 100644 --- a/apps/studio/data/integrations/aws-redirect-query.ts +++ b/apps/studio/data/integrations/aws-redirect-query.ts @@ -28,11 +28,9 @@ export const useAwsRedirectQuery = ( { organizationSlug }: AwsRedirectVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - integrationKeys.awsRedirect(organizationSlug), - ({ signal }) => getAwsRedirect({ organizationSlug }, signal), - { - enabled: enabled && typeof organizationSlug !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: integrationKeys.awsRedirect(organizationSlug), + queryFn: ({ signal }) => getAwsRedirect({ organizationSlug }, signal), + enabled: enabled && typeof organizationSlug !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/integrations/github-authorization-create-mutation.ts b/apps/studio/data/integrations/github-authorization-create-mutation.ts index a9f69142bbc3c..c812e16faa25a 100644 --- a/apps/studio/data/integrations/github-authorization-create-mutation.ts +++ b/apps/studio/data/integrations/github-authorization-create-mutation.ts @@ -48,7 +48,8 @@ export const useGitHubAuthorizationCreateMutation = ({ GitHubAuthorizationCreateData, ResponseError, GitHubAuthorizationCreateVariables - >((vars) => createGitHubAuthorization(vars), { + >({ + mutationFn: (vars) => createGitHubAuthorization(vars), async onSuccess(data, variables, context) { await onSuccess?.(data, variables, context) }, diff --git a/apps/studio/data/integrations/github-authorization-query.ts b/apps/studio/data/integrations/github-authorization-query.ts index 03b1846330dd5..8bde6edd0fb4d 100644 --- a/apps/studio/data/integrations/github-authorization-query.ts +++ b/apps/studio/data/integrations/github-authorization-query.ts @@ -22,9 +22,11 @@ export const useGitHubAuthorizationQuery = ({ enabled = true, ...options }: UseQueryOptions = {}) => { - return useQuery( - integrationKeys.githubAuthorization(), - ({ signal }) => getGitHubAuthorization(signal), - { enabled, staleTime: 0, ...options } - ) + return useQuery({ + queryKey: integrationKeys.githubAuthorization(), + queryFn: ({ signal }) => getGitHubAuthorization(signal), + enabled, + staleTime: 0, + ...options, + }) } diff --git a/apps/studio/data/integrations/github-branch-check-query.ts b/apps/studio/data/integrations/github-branch-check-query.ts index b7f98fbe41602..dd543cf89d3b3 100644 --- a/apps/studio/data/integrations/github-branch-check-query.ts +++ b/apps/studio/data/integrations/github-branch-check-query.ts @@ -40,20 +40,18 @@ export const useCheckGithubBranchValidity = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => checkGithubBranchValidity(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to check GitHub branch: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => checkGithubBranchValidity(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to check GitHub branch: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/integrations/github-branches-query.ts b/apps/studio/data/integrations/github-branches-query.ts index 361039e1397e8..d8d441b848912 100644 --- a/apps/studio/data/integrations/github-branches-query.ts +++ b/apps/studio/data/integrations/github-branches-query.ts @@ -32,11 +32,9 @@ export const useGitHubBranchesQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - integrationKeys.githubBranchesList(connectionId), - ({ signal }) => getGitHubBranches({ connectionId }, signal), - { - enabled: enabled && typeof connectionId !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: integrationKeys.githubBranchesList(connectionId), + queryFn: ({ signal }) => getGitHubBranches({ connectionId }, signal), + enabled: enabled && typeof connectionId !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/integrations/github-connection-create-mutation.ts b/apps/studio/data/integrations/github-connection-create-mutation.ts index f1801cba2db0c..69751280141c0 100644 --- a/apps/studio/data/integrations/github-connection-create-mutation.ts +++ b/apps/studio/data/integrations/github-connection-create-mutation.ts @@ -31,25 +31,23 @@ export const useGitHubConnectionCreateMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createGitHubConnection(vars), - { - async onSuccess(data, variables, context) { - await Promise.all([ - queryClient.invalidateQueries( - integrationKeys.githubConnectionsList(variables.organizationId) - ), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create GitHub connection: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createGitHubConnection(vars), + async onSuccess(data, variables, context) { + await Promise.all([ + queryClient.invalidateQueries( + integrationKeys.githubConnectionsList(variables.organizationId) + ), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create GitHub connection: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/integrations/github-connection-delete-mutation.ts b/apps/studio/data/integrations/github-connection-delete-mutation.ts index ad451eb5741fb..178ea3988a056 100644 --- a/apps/studio/data/integrations/github-connection-delete-mutation.ts +++ b/apps/studio/data/integrations/github-connection-delete-mutation.ts @@ -31,25 +31,23 @@ export const useGitHubConnectionDeleteMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (args) => deleteConnection(args), - { - async onSuccess(data, variables, context) { - await Promise.all([ - queryClient.invalidateQueries( - integrationKeys.githubConnectionsList(variables.organizationId) - ), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete GitHub connection: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (args) => deleteConnection(args), + async onSuccess(data, variables, context) { + await Promise.all([ + queryClient.invalidateQueries( + integrationKeys.githubConnectionsList(variables.organizationId) + ), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete GitHub connection: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/integrations/github-connection-update-mutation.ts b/apps/studio/data/integrations/github-connection-update-mutation.ts index d15462ea50276..640d604cd792b 100644 --- a/apps/studio/data/integrations/github-connection-update-mutation.ts +++ b/apps/studio/data/integrations/github-connection-update-mutation.ts @@ -37,25 +37,23 @@ export const useGitHubConnectionUpdateMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (args) => updateConnection(args), - { - async onSuccess(data, variables, context) { - await Promise.all([ - queryClient.invalidateQueries( - integrationKeys.githubConnectionsList(variables.organizationId) - ), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update GitHub connection: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (args) => updateConnection(args), + async onSuccess(data, variables, context) { + await Promise.all([ + queryClient.invalidateQueries( + integrationKeys.githubConnectionsList(variables.organizationId) + ), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update GitHub connection: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/integrations/github-connections-query.ts b/apps/studio/data/integrations/github-connections-query.ts index 559fd30fcd66e..6f031f1344d82 100644 --- a/apps/studio/data/integrations/github-connections-query.ts +++ b/apps/studio/data/integrations/github-connections-query.ts @@ -39,13 +39,11 @@ export const useGitHubConnectionsQuery = ( ...options }: UseQueryOptions = {} ) => { - return useQuery( - integrationKeys.githubConnectionsList(organizationId), - ({ signal }) => getGitHubConnections({ organizationId }, signal), - { - enabled: enabled && typeof organizationId !== 'undefined', - staleTime: 30 * 60 * 1000, // 30 minutes - ...options, - } - ) + return useQuery({ + queryKey: integrationKeys.githubConnectionsList(organizationId), + queryFn: ({ signal }) => getGitHubConnections({ organizationId }, signal), + enabled: enabled && typeof organizationId !== 'undefined', + staleTime: 30 * 60 * 1000, + ...options, + }) } diff --git a/apps/studio/data/integrations/github-repositories-query.ts b/apps/studio/data/integrations/github-repositories-query.ts index 31079437e9a97..44ff23ab01840 100644 --- a/apps/studio/data/integrations/github-repositories-query.ts +++ b/apps/studio/data/integrations/github-repositories-query.ts @@ -23,9 +23,11 @@ export const useGitHubRepositoriesQuery = ({ enabled = true, ...options }: UseQueryOptions = {}) => { - return useQuery( - integrationKeys.githubRepositoriesList(), - ({ signal }) => getGitHubRepositories(signal), - { enabled, staleTime: 0, ...options } - ) + return useQuery({ + queryKey: integrationKeys.githubRepositoriesList(), + queryFn: ({ signal }) => getGitHubRepositories(signal), + enabled, + staleTime: 0, + ...options, + }) } diff --git a/apps/studio/data/integrations/integrations-query-org-only.ts b/apps/studio/data/integrations/integrations-query-org-only.ts index e3904f188ad29..ce6fdbb6111d0 100644 --- a/apps/studio/data/integrations/integrations-query-org-only.ts +++ b/apps/studio/data/integrations/integrations-query-org-only.ts @@ -27,12 +27,10 @@ export const useOrgIntegrationsQuery = ( { orgSlug }: IntegrationsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - integrationKeys.integrationsListWithOrg(orgSlug), - ({ signal }) => getIntegrations({ orgSlug }, signal), - { - enabled: enabled && typeof orgSlug !== 'undefined', - staleTime: 30 * 60 * 1000, // 30 minutes - ...options, - } - ) + useQuery({ + queryKey: integrationKeys.integrationsListWithOrg(orgSlug), + queryFn: ({ signal }) => getIntegrations({ orgSlug }, signal), + enabled: enabled && typeof orgSlug !== 'undefined', + staleTime: 30 * 60 * 1000, + ...options, + }) diff --git a/apps/studio/data/integrations/integrations-query.ts b/apps/studio/data/integrations/integrations-query.ts index e922fb4042a6c..efdae8e3eb27a 100644 --- a/apps/studio/data/integrations/integrations-query.ts +++ b/apps/studio/data/integrations/integrations-query.ts @@ -21,12 +21,10 @@ export const useIntegrationsQuery = ({ enabled = true, ...options }: UseQueryOptions = {}) => - useQuery( - integrationKeys.integrationsList(), - ({ signal }) => getIntegrations(signal), - { - enabled: enabled, - staleTime: 30 * 60 * 1000, // 30 minutes - ...options, - } - ) + useQuery({ + queryKey: integrationKeys.integrationsList(), + queryFn: ({ signal }) => getIntegrations(signal), + enabled: enabled, + staleTime: 30 * 60 * 1000, + ...options, + }) diff --git a/apps/studio/data/integrations/integrations-vercel-connection-sync-envs-mutation.ts b/apps/studio/data/integrations/integrations-vercel-connection-sync-envs-mutation.ts index c80a5a0711095..862350bf11b3e 100644 --- a/apps/studio/data/integrations/integrations-vercel-connection-sync-envs-mutation.ts +++ b/apps/studio/data/integrations/integrations-vercel-connection-sync-envs-mutation.ts @@ -44,7 +44,8 @@ export const useIntegrationsVercelConnectionSyncEnvsMutation = ({ IntegrationsVercelConnectionSyncEnvsData, ResponseError, IntegrationsVercelConnectionSyncEnvsVariables - >((vars) => syncEnvsIntegrationsVercelConnection(vars), { + >({ + mutationFn: (vars) => syncEnvsIntegrationsVercelConnection(vars), async onSuccess(data, variables, context) { await onSuccess?.(data, variables, context) }, diff --git a/apps/studio/data/integrations/integrations-vercel-connections-create-mutation.ts b/apps/studio/data/integrations/integrations-vercel-connections-create-mutation.ts index 8596b60ed0c6c..1eddc25626945 100644 --- a/apps/studio/data/integrations/integrations-vercel-connections-create-mutation.ts +++ b/apps/studio/data/integrations/integrations-vercel-connections-create-mutation.ts @@ -48,7 +48,8 @@ export const useIntegrationVercelConnectionsCreateMutation = ({ IntegrationVercelConnectionsCreateData, ResponseError, IntegrationConnectionsCreateVariables - >((vars) => createIntegrationVercelConnections(vars), { + >({ + mutationFn: (vars) => createIntegrationVercelConnections(vars), async onSuccess(data, variables, context) { await Promise.all([ queryClient.invalidateQueries(integrationKeys.integrationsList()), diff --git a/apps/studio/data/integrations/integrations-vercel-installed-connection-delete-mutation.ts b/apps/studio/data/integrations/integrations-vercel-installed-connection-delete-mutation.ts index 13c93f60ccef7..2704aaf1a4c42 100644 --- a/apps/studio/data/integrations/integrations-vercel-installed-connection-delete-mutation.ts +++ b/apps/studio/data/integrations/integrations-vercel-installed-connection-delete-mutation.ts @@ -37,30 +37,28 @@ export const useIntegrationsVercelInstalledConnectionDeleteMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (args) => deleteConnection(args), - { - async onSuccess(data, variables, context) { - await Promise.all([ - queryClient.invalidateQueries(integrationKeys.integrationsList()), - queryClient.invalidateQueries(integrationKeys.integrationsListWithOrg(variables.orgSlug)), - queryClient.invalidateQueries( - integrationKeys.vercelProjectList(variables.organization_integration_id) - ), - queryClient.invalidateQueries( - integrationKeys.vercelConnectionsList(variables.organization_integration_id) - ), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete Vercel connection: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (args) => deleteConnection(args), + async onSuccess(data, variables, context) { + await Promise.all([ + queryClient.invalidateQueries(integrationKeys.integrationsList()), + queryClient.invalidateQueries(integrationKeys.integrationsListWithOrg(variables.orgSlug)), + queryClient.invalidateQueries( + integrationKeys.vercelProjectList(variables.organization_integration_id) + ), + queryClient.invalidateQueries( + integrationKeys.vercelConnectionsList(variables.organization_integration_id) + ), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete Vercel connection: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/integrations/integrations-vercel-projects-query.ts b/apps/studio/data/integrations/integrations-vercel-projects-query.ts index cfdf393725134..f504315d860e7 100644 --- a/apps/studio/data/integrations/integrations-vercel-projects-query.ts +++ b/apps/studio/data/integrations/integrations-vercel-projects-query.ts @@ -44,11 +44,9 @@ export const useVercelProjectsQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - integrationKeys.vercelProjectList(organization_integration_id), - ({ signal }) => getVercelProjects({ organization_integration_id }, signal), - { - enabled: enabled && typeof organization_integration_id !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: integrationKeys.vercelProjectList(organization_integration_id), + queryFn: ({ signal }) => getVercelProjects({ organization_integration_id }, signal), + enabled: enabled && typeof organization_integration_id !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/integrations/vercel-connection-update-mutate.ts b/apps/studio/data/integrations/vercel-connection-update-mutate.ts index b210d6df67fe5..0e2788b7f69cd 100644 --- a/apps/studio/data/integrations/vercel-connection-update-mutate.ts +++ b/apps/studio/data/integrations/vercel-connection-update-mutate.ts @@ -44,23 +44,21 @@ export const useVercelConnectionUpdateMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateVercelConnection(vars), - { - async onSuccess(data, variables, context) { - await queryClient.invalidateQueries( - integrationKeys.vercelConnectionsList(variables.organizationIntegrationId) - ) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update Vercel connection: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateVercelConnection(vars), + async onSuccess(data, variables, context) { + await queryClient.invalidateQueries( + integrationKeys.vercelConnectionsList(variables.organizationIntegrationId) + ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update Vercel connection: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/integrations/vercel-integration-create-mutation.ts b/apps/studio/data/integrations/vercel-integration-create-mutation.ts index f3d1315c29a65..d14c89ef74a38 100644 --- a/apps/studio/data/integrations/vercel-integration-create-mutation.ts +++ b/apps/studio/data/integrations/vercel-integration-create-mutation.ts @@ -52,25 +52,23 @@ export const useVercelIntegrationCreateMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createVercelIntegration(vars), - { - async onSuccess(data, variables, context) { - await Promise.all([ - queryClient.invalidateQueries(integrationKeys.integrationsList()), - queryClient.invalidateQueries(integrationKeys.integrationsListWithOrg(variables.orgSlug)), - queryClient.invalidateQueries(integrationKeys.vercelProjectList(data.id)), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create Vercel integration: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createVercelIntegration(vars), + async onSuccess(data, variables, context) { + await Promise.all([ + queryClient.invalidateQueries(integrationKeys.integrationsList()), + queryClient.invalidateQueries(integrationKeys.integrationsListWithOrg(variables.orgSlug)), + queryClient.invalidateQueries(integrationKeys.vercelProjectList(data.id)), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create Vercel integration: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/integrations/vercel-redirect-query.ts b/apps/studio/data/integrations/vercel-redirect-query.ts index 3b25224fb0d45..08cd018a96ea5 100644 --- a/apps/studio/data/integrations/vercel-redirect-query.ts +++ b/apps/studio/data/integrations/vercel-redirect-query.ts @@ -32,11 +32,9 @@ export const useVercelRedirectQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - integrationKeys.vercelRedirect(installationId), - ({ signal }) => getVercelRedirect({ installationId }, signal), - { - enabled: enabled && typeof installationId !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: integrationKeys.vercelRedirect(installationId), + queryFn: ({ signal }) => getVercelRedirect({ installationId }, signal), + enabled: enabled && typeof installationId !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/invoices/invoice-payment-link-mutation.ts b/apps/studio/data/invoices/invoice-payment-link-mutation.ts index d4ea25ca3e5a1..cc452ad32782d 100644 --- a/apps/studio/data/invoices/invoice-payment-link-mutation.ts +++ b/apps/studio/data/invoices/invoice-payment-link-mutation.ts @@ -44,22 +44,18 @@ export const useInvoicePaymentLinkGetMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateInvoicePaymentLink(vars), - { - async onError(error, variables, context) { - // In case of an error, there is a good chance that the invoice status has changed, so we invalidate the cache to reflect the updated status - await Promise.all([ - queryClient.invalidateQueries(invoicesKeys.listAndCount(variables.slug)), - ]) - - if (onError === undefined) { - toast.error(error.message) - } else { - onError(error, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateInvoicePaymentLink(vars), + async onError(error, variables, context) { + // In case of an error, there is a good chance that the invoice status has changed, so we invalidate the cache to reflect the updated status + await Promise.all([queryClient.invalidateQueries(invoicesKeys.listAndCount(variables.slug))]) + + if (onError === undefined) { + toast.error(error.message) + } else { + onError(error, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/invoices/invoice-query.ts b/apps/studio/data/invoices/invoice-query.ts index d3e09dcf0f087..638d8f90a45ec 100644 --- a/apps/studio/data/invoices/invoice-query.ts +++ b/apps/studio/data/invoices/invoice-query.ts @@ -31,11 +31,9 @@ export const useInvoiceQuery = ( { invoiceId: id }: InvoiceVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - invoicesKeys.invoice(id), - ({ signal }) => getInvoice({ invoiceId: id }, signal), - { - enabled: enabled && typeof id !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: invoicesKeys.invoice(id), + queryFn: ({ signal }) => getInvoice({ invoiceId: id }, signal), + enabled: enabled && typeof id !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/invoices/invoices-count-query.ts b/apps/studio/data/invoices/invoices-count-query.ts index 0491e361c4931..a189cc91236cd 100644 --- a/apps/studio/data/invoices/invoices-count-query.ts +++ b/apps/studio/data/invoices/invoices-count-query.ts @@ -27,11 +27,9 @@ export const useInvoicesCountQuery = ( { slug }: InvoicesCountVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - invoicesKeys.count(slug), - ({ signal }) => getInvoicesCount({ slug }, signal), - { - enabled: enabled && typeof slug !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: invoicesKeys.count(slug), + queryFn: ({ signal }) => getInvoicesCount({ slug }, signal), + enabled: enabled && typeof slug !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/invoices/invoices-overdue-query.ts b/apps/studio/data/invoices/invoices-overdue-query.ts index 30759d9be36b5..b31a76bdb26cb 100644 --- a/apps/studio/data/invoices/invoices-overdue-query.ts +++ b/apps/studio/data/invoices/invoices-overdue-query.ts @@ -24,13 +24,11 @@ export const useOverdueInvoicesQuery = ({ ...options }: UseQueryOptions = {}) => { const isLoggedIn = useIsLoggedIn() - return useQuery( - invoicesKeys.overdueInvoices(), - ({ signal }) => getOverdueInvoices(signal), - { - enabled: enabled && isLoggedIn && IS_PLATFORM, - staleTime: 30 * 60 * 1000, // 30 minutes - ...options, - } - ) + return useQuery({ + queryKey: invoicesKeys.overdueInvoices(), + queryFn: ({ signal }) => getOverdueInvoices(signal), + enabled: enabled && isLoggedIn && IS_PLATFORM, + staleTime: 30 * 60 * 1000, + ...options, + }) } diff --git a/apps/studio/data/invoices/invoices-query.ts b/apps/studio/data/invoices/invoices-query.ts index 23747215b08ca..ff3118d31e97e 100644 --- a/apps/studio/data/invoices/invoices-query.ts +++ b/apps/studio/data/invoices/invoices-query.ts @@ -35,11 +35,9 @@ export const useInvoicesQuery = ( { enabled = true, ...options }: UseQueryOptions = {} ) => // [Joshen] Switch to useInfiniteQuery - useQuery( - invoicesKeys.list(slug, offset), - ({ signal }) => getInvoices({ slug, offset, limit }, signal), - { - enabled: enabled && typeof slug !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: invoicesKeys.list(slug, offset), + queryFn: ({ signal }) => getInvoices({ slug, offset, limit }, signal), + enabled: enabled && typeof slug !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/invoices/org-invoice-upcoming-query.ts b/apps/studio/data/invoices/org-invoice-upcoming-query.ts index 0a2d42cfb9a13..18aeb58b9367f 100644 --- a/apps/studio/data/invoices/org-invoice-upcoming-query.ts +++ b/apps/studio/data/invoices/org-invoice-upcoming-query.ts @@ -70,11 +70,9 @@ export const useOrgUpcomingInvoiceQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - invoicesKeys.orgUpcomingPreview(orgSlug), - ({ signal }) => getUpcomingInvoice({ orgSlug }, signal), - { - enabled: enabled && typeof orgSlug !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: invoicesKeys.orgUpcomingPreview(orgSlug), + queryFn: ({ signal }) => getUpcomingInvoice({ orgSlug }, signal), + enabled: enabled && typeof orgSlug !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/jwt-signing-keys/jwt-signing-key-create-mutation.ts b/apps/studio/data/jwt-signing-keys/jwt-signing-key-create-mutation.ts index 7098b226c99c5..fdf264b4594ec 100644 --- a/apps/studio/data/jwt-signing-keys/jwt-signing-key-create-mutation.ts +++ b/apps/studio/data/jwt-signing-keys/jwt-signing-key-create-mutation.ts @@ -43,24 +43,22 @@ export const useJWTSigningKeyCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createJWTSigningKey(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables + return useMutation({ + mutationFn: (vars) => createJWTSigningKey(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables - await queryClient.invalidateQueries(jwtSigningKeysKeys.list(projectRef)) + await queryClient.invalidateQueries(jwtSigningKeysKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create new JWT signing key: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create new JWT signing key: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/jwt-signing-keys/jwt-signing-key-delete-mutation.ts b/apps/studio/data/jwt-signing-keys/jwt-signing-key-delete-mutation.ts index d39179436c9ca..64a58b5696ce4 100644 --- a/apps/studio/data/jwt-signing-keys/jwt-signing-key-delete-mutation.ts +++ b/apps/studio/data/jwt-signing-keys/jwt-signing-key-delete-mutation.ts @@ -35,24 +35,22 @@ export const useJWTSigningKeyDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteJWTSigningKey(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - - await queryClient.invalidateQueries(jwtSigningKeysKeys.list(projectRef)) - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete JWT signing key: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteJWTSigningKey(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + + await queryClient.invalidateQueries(jwtSigningKeysKeys.list(projectRef)) + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete JWT signing key: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/jwt-signing-keys/jwt-signing-key-update-mutation.ts b/apps/studio/data/jwt-signing-keys/jwt-signing-key-update-mutation.ts index a406194980e07..edbc4f2bf89ae 100644 --- a/apps/studio/data/jwt-signing-keys/jwt-signing-key-update-mutation.ts +++ b/apps/studio/data/jwt-signing-keys/jwt-signing-key-update-mutation.ts @@ -39,24 +39,22 @@ export const useJWTSigningKeyUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateJWTSigningKey(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - - await queryClient.invalidateQueries(jwtSigningKeysKeys.list(projectRef)) - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update new JWT signing key: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateJWTSigningKey(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + + await queryClient.invalidateQueries(jwtSigningKeysKeys.list(projectRef)) + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update new JWT signing key: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/jwt-signing-keys/jwt-signing-keys-query.ts b/apps/studio/data/jwt-signing-keys/jwt-signing-keys-query.ts index 83cf2a5addcfc..ceaebae9dda92 100644 --- a/apps/studio/data/jwt-signing-keys/jwt-signing-keys-query.ts +++ b/apps/studio/data/jwt-signing-keys/jwt-signing-keys-query.ts @@ -33,11 +33,9 @@ export const useJWTSigningKeysQuery = ( { projectRef }: JWTSigningKeysVariables, { enabled, ...options }: UseQueryOptions = {} ) => - useQuery( - jwtSigningKeysKeys.list(projectRef), - ({ signal }) => getJWTSigningKeys({ projectRef }, signal), - { - enabled: enabled && !!projectRef, - ...options, - } - ) + useQuery({ + queryKey: jwtSigningKeysKeys.list(projectRef), + queryFn: ({ signal }) => getJWTSigningKeys({ projectRef }, signal), + enabled: enabled && !!projectRef, + ...options, + }) diff --git a/apps/studio/data/jwt-signing-keys/legacy-jwt-signing-key-create-mutation.ts b/apps/studio/data/jwt-signing-keys/legacy-jwt-signing-key-create-mutation.ts index 52fd030e2c615..d20e775c79647 100644 --- a/apps/studio/data/jwt-signing-keys/legacy-jwt-signing-key-create-mutation.ts +++ b/apps/studio/data/jwt-signing-keys/legacy-jwt-signing-key-create-mutation.ts @@ -42,7 +42,8 @@ export const useLegacyJWTSigningKeyCreateMutation = ({ LegacyJWTSigningKeyCreateData, ResponseError, LegacyJWTSigningKeyCreateVariables - >((vars) => createLegacyJWTSigningKey(vars), { + >({ + mutationFn: (vars) => createLegacyJWTSigningKey(vars), async onSuccess(data, variables, context) { const { projectRef } = variables diff --git a/apps/studio/data/jwt-signing-keys/legacy-jwt-signing-key-query.ts b/apps/studio/data/jwt-signing-keys/legacy-jwt-signing-key-query.ts index f7d66873178ab..9bb2d49310722 100644 --- a/apps/studio/data/jwt-signing-keys/legacy-jwt-signing-key-query.ts +++ b/apps/studio/data/jwt-signing-keys/legacy-jwt-signing-key-query.ts @@ -32,13 +32,11 @@ export const useLegacyJWTSigningKeyQuery = ( { projectRef }: LegacyJWTSigningKeyVariables, { enabled, ...options }: UseQueryOptions = {} ) => - useQuery( - jwtSigningKeysKeys.legacy(projectRef), - ({ signal }) => getLegacyJWTSigningKey({ projectRef }, signal), - { - enabled: enabled && !!projectRef, - retry: false, - refetchOnWindowFocus: false, - ...options, - } - ) + useQuery({ + queryKey: jwtSigningKeysKeys.legacy(projectRef), + queryFn: ({ signal }) => getLegacyJWTSigningKey({ projectRef }, signal), + enabled: enabled && !!projectRef, + retry: false, + refetchOnWindowFocus: false, + ...options, + }) diff --git a/apps/studio/data/lint/create-lint-rule-mutation.ts b/apps/studio/data/lint/create-lint-rule-mutation.ts index ae8bdd527d5a7..e128c5345e459 100644 --- a/apps/studio/data/lint/create-lint-rule-mutation.ts +++ b/apps/studio/data/lint/create-lint-rule-mutation.ts @@ -36,25 +36,23 @@ export const useLintRuleCreateMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createLintRule(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await Promise.all([ - queryClient.invalidateQueries(lintKeys.lintRules(projectRef)), - queryClient.invalidateQueries(lintKeys.lint(projectRef)), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create lint rule: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createLintRule(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await Promise.all([ + queryClient.invalidateQueries(lintKeys.lintRules(projectRef)), + queryClient.invalidateQueries(lintKeys.lint(projectRef)), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create lint rule: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/lint/delete-lint-rule-mutation.ts b/apps/studio/data/lint/delete-lint-rule-mutation.ts index cf6538fdff5f3..507745b75754a 100644 --- a/apps/studio/data/lint/delete-lint-rule-mutation.ts +++ b/apps/studio/data/lint/delete-lint-rule-mutation.ts @@ -30,25 +30,23 @@ export const useLintRuleDeleteMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteLintRule(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await Promise.all([ - queryClient.invalidateQueries(lintKeys.lintRules(projectRef)), - queryClient.invalidateQueries(lintKeys.lint(projectRef)), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete lint rule: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteLintRule(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await Promise.all([ + queryClient.invalidateQueries(lintKeys.lintRules(projectRef)), + queryClient.invalidateQueries(lintKeys.lint(projectRef)), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete lint rule: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/lint/lint-query.ts b/apps/studio/data/lint/lint-query.ts index ca970d5d4e837..3e84f485da370 100644 --- a/apps/studio/data/lint/lint-query.ts +++ b/apps/studio/data/lint/lint-query.ts @@ -37,12 +37,10 @@ export const useProjectLintsQuery = ( const { data: project } = useSelectedProjectQuery() const isActive = project?.status === PROJECT_STATUS.ACTIVE_HEALTHY - return useQuery( - lintKeys.lint(projectRef), - ({ signal }) => getProjectLints({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && isActive, - ...options, - } - ) + return useQuery({ + queryKey: lintKeys.lint(projectRef), + queryFn: ({ signal }) => getProjectLints({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && isActive, + ...options, + }) } diff --git a/apps/studio/data/lint/lint-rules-query.ts b/apps/studio/data/lint/lint-rules-query.ts index 414a221b2ac21..37778d3b81e16 100644 --- a/apps/studio/data/lint/lint-rules-query.ts +++ b/apps/studio/data/lint/lint-rules-query.ts @@ -42,12 +42,10 @@ export const useProjectLintRulesQuery = ( const { data: project } = useSelectedProjectQuery() const isActive = project?.status === PROJECT_STATUS.ACTIVE_HEALTHY - return useQuery( - lintKeys.lintRules(projectRef), - ({ signal }) => getProjectLintRules({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && isActive, - ...options, - } - ) + return useQuery({ + queryKey: lintKeys.lintRules(projectRef), + queryFn: ({ signal }) => getProjectLintRules({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && isActive, + ...options, + }) } diff --git a/apps/studio/data/log-drains/create-log-drain-mutation.ts b/apps/studio/data/log-drains/create-log-drain-mutation.ts index 3e6b4a4a060f1..9e77581c1f2ee 100644 --- a/apps/studio/data/log-drains/create-log-drain-mutation.ts +++ b/apps/studio/data/log-drains/create-log-drain-mutation.ts @@ -41,24 +41,22 @@ export const useCreateLogDrainMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createLogDrain(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables + return useMutation({ + mutationFn: (vars) => createLogDrain(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables - await queryClient.invalidateQueries(logDrainsKeys.list(projectRef)) + await queryClient.invalidateQueries(logDrainsKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to mutate: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to mutate: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/log-drains/delete-log-drain-mutation.ts b/apps/studio/data/log-drains/delete-log-drain-mutation.ts index a470f8ea06e28..862a0f0074c6c 100644 --- a/apps/studio/data/log-drains/delete-log-drain-mutation.ts +++ b/apps/studio/data/log-drains/delete-log-drain-mutation.ts @@ -32,24 +32,22 @@ export const useDeleteLogDrainMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteLogDrain(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - - await queryClient.invalidateQueries(logDrainsKeys.list(projectRef)) - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to mutate: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteLogDrain(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + + await queryClient.invalidateQueries(logDrainsKeys.list(projectRef)) + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to mutate: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/log-drains/log-drains-query.ts b/apps/studio/data/log-drains/log-drains-query.ts index 41cf0284eb569..e47669673613e 100644 --- a/apps/studio/data/log-drains/log-drains-query.ts +++ b/apps/studio/data/log-drains/log-drains-query.ts @@ -32,12 +32,10 @@ export const useLogDrainsQuery = ( { ref }: LogDrainsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - logDrainsKeys.list(ref), - ({ signal }) => getLogDrains({ ref }, signal), - { - enabled: enabled && !!ref, - refetchOnMount: false, - ...options, - } - ) + useQuery({ + queryKey: logDrainsKeys.list(ref), + queryFn: ({ signal }) => getLogDrains({ ref }, signal), + enabled: enabled && !!ref, + refetchOnMount: false, + ...options, + }) diff --git a/apps/studio/data/log-drains/update-log-drain-mutation.ts b/apps/studio/data/log-drains/update-log-drain-mutation.ts index 14463173f589f..bec7a574481db 100644 --- a/apps/studio/data/log-drains/update-log-drain-mutation.ts +++ b/apps/studio/data/log-drains/update-log-drain-mutation.ts @@ -46,24 +46,22 @@ export const useUpdateLogDrainMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateLogDrain(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables + return useMutation({ + mutationFn: (vars) => updateLogDrain(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables - await queryClient.invalidateQueries(logDrainsKeys.list(projectRef)) + await queryClient.invalidateQueries(logDrainsKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to mutate: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to mutate: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/logs/get-unified-logs.ts b/apps/studio/data/logs/get-unified-logs.ts index 7280249c5b2f3..66ebdfb4ee552 100644 --- a/apps/studio/data/logs/get-unified-logs.ts +++ b/apps/studio/data/logs/get-unified-logs.ts @@ -72,20 +72,18 @@ export const useGetUnifiedLogsMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => retrieveUnifiedLogs(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to retrieve logs: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => retrieveUnifiedLogs(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to retrieve logs: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/logs/unified-log-inspection-query.ts b/apps/studio/data/logs/unified-log-inspection-query.ts index 3253e54fe1541..68c9bec82569f 100644 --- a/apps/studio/data/logs/unified-log-inspection-query.ts +++ b/apps/studio/data/logs/unified-log-inspection-query.ts @@ -180,12 +180,10 @@ export const useUnifiedLogInspectionQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - logsKeys.serviceFlow(projectRef, search, logId), - ({ signal }) => getUnifiedLogInspection({ projectRef, logId, type, search }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...UNIFIED_LOGS_QUERY_OPTIONS, - ...options, - } - ) + useQuery({ + queryKey: logsKeys.serviceFlow(projectRef, search, logId), + queryFn: ({ signal }) => getUnifiedLogInspection({ projectRef, logId, type, search }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...UNIFIED_LOGS_QUERY_OPTIONS, + ...options, + }) diff --git a/apps/studio/data/logs/unified-logs-chart-query.ts b/apps/studio/data/logs/unified-logs-chart-query.ts index b2132dd1e489b..90039ac14848f 100644 --- a/apps/studio/data/logs/unified-logs-chart-query.ts +++ b/apps/studio/data/logs/unified-logs-chart-query.ts @@ -150,13 +150,11 @@ export const useUnifiedLogsChartQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - logsKeys.unifiedLogsChart(projectRef, search), - ({ signal }) => getUnifiedLogsChart({ projectRef, search }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - keepPreviousData: true, - ...UNIFIED_LOGS_QUERY_OPTIONS, - ...options, - } - ) + useQuery({ + queryKey: logsKeys.unifiedLogsChart(projectRef, search), + queryFn: ({ signal }) => getUnifiedLogsChart({ projectRef, search }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + keepPreviousData: true, + ...UNIFIED_LOGS_QUERY_OPTIONS, + ...options, + }) diff --git a/apps/studio/data/logs/unified-logs-count-query.ts b/apps/studio/data/logs/unified-logs-count-query.ts index 7bd0d1dca2fd6..b6511469dc589 100644 --- a/apps/studio/data/logs/unified-logs-count-query.ts +++ b/apps/studio/data/logs/unified-logs-count-query.ts @@ -83,12 +83,10 @@ export const useUnifiedLogsCountQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - logsKeys.unifiedLogsCount(projectRef, search), - ({ signal }) => getUnifiedLogsCount({ projectRef, search }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...UNIFIED_LOGS_QUERY_OPTIONS, - ...options, - } - ) + useQuery({ + queryKey: logsKeys.unifiedLogsCount(projectRef, search), + queryFn: ({ signal }) => getUnifiedLogsCount({ projectRef, search }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...UNIFIED_LOGS_QUERY_OPTIONS, + ...options, + }) diff --git a/apps/studio/data/logs/unified-logs-facet-count-query.ts b/apps/studio/data/logs/unified-logs-facet-count-query.ts index dea0d5a885c69..c6241a51e1251 100644 --- a/apps/studio/data/logs/unified-logs-facet-count-query.ts +++ b/apps/studio/data/logs/unified-logs-facet-count-query.ts @@ -53,12 +53,11 @@ export const useUnifiedLogsFacetCountQuery = ...options }: UseQueryOptions = {} ) => - useQuery( - logsKeys.unifiedLogsFacetCount(projectRef, facet, facetSearch, search), - ({ signal }) => getUnifiedLogsFacetCount({ projectRef, search, facet, facetSearch }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...UNIFIED_LOGS_QUERY_OPTIONS, - ...options, - } - ) + useQuery({ + queryKey: logsKeys.unifiedLogsFacetCount(projectRef, facet, facetSearch, search), + queryFn: ({ signal }) => + getUnifiedLogsFacetCount({ projectRef, search, facet, facetSearch }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...UNIFIED_LOGS_QUERY_OPTIONS, + ...options, + }) diff --git a/apps/studio/data/materialized-views/materialized-views-query.ts b/apps/studio/data/materialized-views/materialized-views-query.ts index 052a3dc337777..331e40543e311 100644 --- a/apps/studio/data/materialized-views/materialized-views-query.ts +++ b/apps/studio/data/materialized-views/materialized-views-query.ts @@ -51,16 +51,12 @@ export const useMaterializedViewsQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - schema + useQuery({ + queryKey: schema ? materializedViewKeys.listBySchema(projectRef, schema) : materializedViewKeys.list(projectRef), - ({ signal }) => getMaterializedViews({ projectRef, connectionString, schema }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - // We're using a staleTime of 0 here because the only way to create a - // materialized view is via SQL, which we don't know about - staleTime: 0, - ...options, - } - ) + queryFn: ({ signal }) => getMaterializedViews({ projectRef, connectionString, schema }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + staleTime: 0, + ...options, + }) diff --git a/apps/studio/data/misc/audit-login-mutation.ts b/apps/studio/data/misc/audit-login-mutation.ts index 376e93017056a..3e2cca8c7a3a7 100644 --- a/apps/studio/data/misc/audit-login-mutation.ts +++ b/apps/studio/data/misc/audit-login-mutation.ts @@ -21,23 +21,21 @@ export const useAddLoginEvent = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => addLoginEvent(), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - Sentry.captureException( - new Error("Failed to add login event to user's audit log", { cause: data }) - ) - if (onError === undefined) { - toast.error(`Failed to add login event: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => addLoginEvent(), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + Sentry.captureException( + new Error("Failed to add login event to user's audit log", { cause: data }) + ) + if (onError === undefined) { + toast.error(`Failed to add login event: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/misc/cli-release-version-query.ts b/apps/studio/data/misc/cli-release-version-query.ts index 098e5eeda4194..3a509167dc2c7 100644 --- a/apps/studio/data/misc/cli-release-version-query.ts +++ b/apps/studio/data/misc/cli-release-version-query.ts @@ -23,8 +23,9 @@ export const useCLIReleaseVersionQuery = ({ enabled = true, ...options }: UseQueryOptions = {}) => - useQuery( - miscKeys.cliReleaseVersion(), - () => getCLIReleaseVersion(), - { enabled: enabled && !IS_PLATFORM, ...options } - ) + useQuery({ + queryKey: miscKeys.cliReleaseVersion(), + queryFn: () => getCLIReleaseVersion(), + enabled: enabled && !IS_PLATFORM, + ...options, + }) diff --git a/apps/studio/data/misc/get-default-region-query.ts b/apps/studio/data/misc/get-default-region-query.ts index 9273e585773a3..104f88ef99120 100644 --- a/apps/studio/data/misc/get-default-region-query.ts +++ b/apps/studio/data/misc/get-default-region-query.ts @@ -76,16 +76,14 @@ export const useDefaultRegionQuery = ( const restrictedPoolFlag = useFlag('defaultRegionRestrictedPool') const restrictedPool = tryParseJson(restrictedPoolFlag) - return useQuery( - miscKeys.defaultRegion(cloudProvider, useRestrictedPool ?? true), - () => getDefaultRegionOption({ cloudProvider, restrictedPool, useRestrictedPool }), - { - enabled: - enabled && typeof cloudProvider !== 'undefined' && typeof restrictedPool !== 'undefined', - retry(failureCount) { - return failureCount < 1 - }, - ...options, - } - ) + return useQuery({ + queryKey: miscKeys.defaultRegion(cloudProvider, useRestrictedPool ?? true), + queryFn: () => getDefaultRegionOption({ cloudProvider, restrictedPool, useRestrictedPool }), + enabled: + enabled && typeof cloudProvider !== 'undefined' && typeof restrictedPool !== 'undefined', + retry(failureCount) { + return failureCount < 1 + }, + ...options, + }) } diff --git a/apps/studio/data/misc/reset-password-mutation.ts b/apps/studio/data/misc/reset-password-mutation.ts index 4f3570118eca6..a2d92053d4c17 100644 --- a/apps/studio/data/misc/reset-password-mutation.ts +++ b/apps/studio/data/misc/reset-password-mutation.ts @@ -33,23 +33,21 @@ export const useResetPasswordMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => resetPassword(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to reset password: ${data.message}`) - } else { - onError(data, variables, context) - } - if (!WHITELIST_ERRORS.some((error) => data.message.includes(error))) { - Sentry.captureMessage('[CRITICAL] Failed to send reset password email: ' + data.message) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => resetPassword(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to reset password: ${data.message}`) + } else { + onError(data, variables, context) + } + if (!WHITELIST_ERRORS.some((error) => data.message.includes(error))) { + Sentry.captureMessage('[CRITICAL] Failed to send reset password email: ' + data.message) + } + }, + ...options, + }) } diff --git a/apps/studio/data/misc/signup-mutation.ts b/apps/studio/data/misc/signup-mutation.ts index ea410aa06e219..c8ecc47f43efd 100644 --- a/apps/studio/data/misc/signup-mutation.ts +++ b/apps/studio/data/misc/signup-mutation.ts @@ -37,7 +37,8 @@ export const useSignUpMutation = ({ onError, ...options }: Omit, 'mutationFn'> = {}) => { - return useMutation((vars) => signup(vars), { + return useMutation({ + mutationFn: (vars) => signup(vars), async onSuccess(data, variables, context) { await onSuccess?.(data, variables, context) }, diff --git a/apps/studio/data/misc/user-ip-address-query.ts b/apps/studio/data/misc/user-ip-address-query.ts index 0dcc15e98db0a..205b6abf59f4b 100644 --- a/apps/studio/data/misc/user-ip-address-query.ts +++ b/apps/studio/data/misc/user-ip-address-query.ts @@ -21,8 +21,9 @@ export const useUserIPAddressQuery = ({ enabled = true, ...options }: UseQueryOptions = {}) => - useQuery( - miscKeys.ipAddress(), - () => getUserIPAddress(), - { enabled: enabled && !IS_PLATFORM, ...options } - ) + useQuery({ + queryKey: miscKeys.ipAddress(), + queryFn: () => getUserIPAddress(), + enabled: enabled && !IS_PLATFORM, + ...options, + }) diff --git a/apps/studio/data/network-restrictions/network-restrictions-query.ts b/apps/studio/data/network-restrictions/network-restrictions-query.ts index bc480fce19c3f..40ac1db39437c 100644 --- a/apps/studio/data/network-restrictions/network-restrictions-query.ts +++ b/apps/studio/data/network-restrictions/network-restrictions-query.ts @@ -55,8 +55,9 @@ export const useNetworkRestrictionsQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - networkRestrictionKeys.list(projectRef), - ({ signal }) => getNetworkRestrictions({ projectRef }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: networkRestrictionKeys.list(projectRef), + queryFn: ({ signal }) => getNetworkRestrictions({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/network-restrictions/network-retrictions-apply-mutation.ts b/apps/studio/data/network-restrictions/network-retrictions-apply-mutation.ts index 29dd3038e4fc2..ec3211b30c76f 100644 --- a/apps/studio/data/network-restrictions/network-retrictions-apply-mutation.ts +++ b/apps/studio/data/network-restrictions/network-retrictions-apply-mutation.ts @@ -47,7 +47,8 @@ export const useNetworkRestrictionsApplyMutation = ({ NetworkRestrictionsApplyData, ResponseError, NetworkRestrictionsApplyVariables - >((vars) => applyNetworkRestrictions(vars), { + >({ + mutationFn: (vars) => applyNetworkRestrictions(vars), async onSuccess(data, variables, context) { const { projectRef } = variables await queryClient.invalidateQueries(networkRestrictionKeys.list(projectRef)) diff --git a/apps/studio/data/notifications/notifications-v2-archive-all-mutation.ts b/apps/studio/data/notifications/notifications-v2-archive-all-mutation.ts index b6f5a875e7dda..56ea6bb19118b 100644 --- a/apps/studio/data/notifications/notifications-v2-archive-all-mutation.ts +++ b/apps/studio/data/notifications/notifications-v2-archive-all-mutation.ts @@ -22,7 +22,8 @@ export const useNotificationsArchiveAllMutation = ({ ...options }: Omit, 'mutationFn'> = {}) => { const queryClient = useQueryClient() - return useMutation(() => archiveAllNotifications(), { + return useMutation({ + mutationFn: () => archiveAllNotifications(), async onSuccess(data, variables, context) { await queryClient.invalidateQueries(notificationKeys.list()) await onSuccess?.(data, variables, context) diff --git a/apps/studio/data/notifications/notifications-v2-summary-query.ts b/apps/studio/data/notifications/notifications-v2-summary-query.ts index 15992ea00901c..ae06cdd01ff5d 100644 --- a/apps/studio/data/notifications/notifications-v2-summary-query.ts +++ b/apps/studio/data/notifications/notifications-v2-summary-query.ts @@ -21,8 +21,8 @@ export type NotificationsError = ResponseError export const useNotificationsSummaryQuery = ( options: UseQueryOptions = {} ) => - useQuery( - notificationKeys.summary(), - ({ signal }) => getNotificationsSummary(signal), - options - ) + useQuery({ + queryKey: notificationKeys.summary(), + queryFn: ({ signal }) => getNotificationsSummary(signal), + ...options, + }) diff --git a/apps/studio/data/notifications/notifications-v2-update-mutation.ts b/apps/studio/data/notifications/notifications-v2-update-mutation.ts index 3a4920e2c5a4c..4cb2bea695ec4 100644 --- a/apps/studio/data/notifications/notifications-v2-update-mutation.ts +++ b/apps/studio/data/notifications/notifications-v2-update-mutation.ts @@ -31,21 +31,19 @@ export const useNotificationsV2UpdateMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateNotifications(vars), - { - async onSuccess(data, variables, context) { - await queryClient.invalidateQueries(['notifications']) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update notifications: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateNotifications(vars), + async onSuccess(data, variables, context) { + await queryClient.invalidateQueries(['notifications']) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update notifications: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/oauth-secrets/client-secret-create-mutation.ts b/apps/studio/data/oauth-secrets/client-secret-create-mutation.ts index 186ac5f879513..13294777e913b 100644 --- a/apps/studio/data/oauth-secrets/client-secret-create-mutation.ts +++ b/apps/studio/data/oauth-secrets/client-secret-create-mutation.ts @@ -28,22 +28,20 @@ export const useClientSecretCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createClientSecret(vars), - { - async onSuccess(data, variables, context) { - const { slug, appId } = variables - await queryClient.invalidateQueries(clientSecretKeys.list(slug, appId)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create client secret: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createClientSecret(vars), + async onSuccess(data, variables, context) { + const { slug, appId } = variables + await queryClient.invalidateQueries(clientSecretKeys.list(slug, appId)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create client secret: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/oauth-secrets/client-secret-delete-mutation.ts b/apps/studio/data/oauth-secrets/client-secret-delete-mutation.ts index caea1911d1b6e..3429b788aae37 100644 --- a/apps/studio/data/oauth-secrets/client-secret-delete-mutation.ts +++ b/apps/studio/data/oauth-secrets/client-secret-delete-mutation.ts @@ -29,22 +29,20 @@ export const useClientSecretDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteClientSecret(vars), - { - async onSuccess(data, variables, context) { - const { slug, appId } = variables - await queryClient.invalidateQueries(clientSecretKeys.list(slug, appId)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete client secret: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteClientSecret(vars), + async onSuccess(data, variables, context) { + const { slug, appId } = variables + await queryClient.invalidateQueries(clientSecretKeys.list(slug, appId)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete client secret: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/oauth-secrets/client-secrets-query.ts b/apps/studio/data/oauth-secrets/client-secrets-query.ts index b69f8d7751dcd..4e5c84389f015 100644 --- a/apps/studio/data/oauth-secrets/client-secrets-query.ts +++ b/apps/studio/data/oauth-secrets/client-secrets-query.ts @@ -51,11 +51,9 @@ export const useClientSecretsQuery = ( { slug, appId }: ClientSecretsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - clientSecretKeys.list(slug, appId), - ({ signal }) => getClientSecrets({ slug, appId }, signal), - { - enabled: enabled && typeof slug !== 'undefined' && typeof appId !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: clientSecretKeys.list(slug, appId), + queryFn: ({ signal }) => getClientSecrets({ slug, appId }, signal), + enabled: enabled && typeof slug !== 'undefined' && typeof appId !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/oauth/authorized-app-revoke-mutation.ts b/apps/studio/data/oauth/authorized-app-revoke-mutation.ts index 9077e1f550f10..22adc77b6240e 100644 --- a/apps/studio/data/oauth/authorized-app-revoke-mutation.ts +++ b/apps/studio/data/oauth/authorized-app-revoke-mutation.ts @@ -34,22 +34,20 @@ export const useAuthorizedAppRevokeMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => revokeAuthorizedApp(vars), - { - async onSuccess(data, variables, context) { - const { slug } = variables - await queryClient.invalidateQueries(oauthAppKeys.authorizedApps(slug)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to revoke application: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => revokeAuthorizedApp(vars), + async onSuccess(data, variables, context) { + const { slug } = variables + await queryClient.invalidateQueries(oauthAppKeys.authorizedApps(slug)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to revoke application: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/oauth/authorized-apps-query.ts b/apps/studio/data/oauth/authorized-apps-query.ts index fed7ff0c13cac..a56657ed174e4 100644 --- a/apps/studio/data/oauth/authorized-apps-query.ts +++ b/apps/studio/data/oauth/authorized-apps-query.ts @@ -39,11 +39,9 @@ export const useAuthorizedAppsQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - oauthAppKeys.authorizedApps(slug), - ({ signal }) => getAuthorizedApps({ slug }, signal), - { - enabled: enabled && typeof slug !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: oauthAppKeys.authorizedApps(slug), + queryFn: ({ signal }) => getAuthorizedApps({ slug }, signal), + enabled: enabled && typeof slug !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/oauth/oauth-app-create-mutation.ts b/apps/studio/data/oauth/oauth-app-create-mutation.ts index 6092b3f340d29..a25d774f44c12 100644 --- a/apps/studio/data/oauth/oauth-app-create-mutation.ts +++ b/apps/studio/data/oauth/oauth-app-create-mutation.ts @@ -53,22 +53,20 @@ export const useOAuthAppCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createOAuthApp(vars), - { - async onSuccess(data, variables, context) { - const { slug } = variables - await queryClient.invalidateQueries(oauthAppKeys.oauthApps(slug)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create OAuth application: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createOAuthApp(vars), + async onSuccess(data, variables, context) { + const { slug } = variables + await queryClient.invalidateQueries(oauthAppKeys.oauthApps(slug)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create OAuth application: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/oauth/oauth-app-delete-mutation.ts b/apps/studio/data/oauth/oauth-app-delete-mutation.ts index 4bf0ca78e470c..d508fd895a181 100644 --- a/apps/studio/data/oauth/oauth-app-delete-mutation.ts +++ b/apps/studio/data/oauth/oauth-app-delete-mutation.ts @@ -34,22 +34,20 @@ export const useOAuthAppDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteOAuthApp(vars), - { - async onSuccess(data, variables, context) { - const { slug } = variables - await queryClient.invalidateQueries(oauthAppKeys.oauthApps(slug)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete application: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteOAuthApp(vars), + async onSuccess(data, variables, context) { + const { slug } = variables + await queryClient.invalidateQueries(oauthAppKeys.oauthApps(slug)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete application: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/oauth/oauth-app-update-mutation.ts b/apps/studio/data/oauth/oauth-app-update-mutation.ts index 0978f6f8b828c..c1ebe217b1b4e 100644 --- a/apps/studio/data/oauth/oauth-app-update-mutation.ts +++ b/apps/studio/data/oauth/oauth-app-update-mutation.ts @@ -57,22 +57,20 @@ export const useOAuthAppUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateOAuthApp(vars), - { - async onSuccess(data, variables, context) { - const { slug } = variables - await queryClient.invalidateQueries(oauthAppKeys.oauthApps(slug)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update application: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateOAuthApp(vars), + async onSuccess(data, variables, context) { + const { slug } = variables + await queryClient.invalidateQueries(oauthAppKeys.oauthApps(slug)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update application: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/oauth/oauth-apps-query.ts b/apps/studio/data/oauth/oauth-apps-query.ts index e8acb2ea9c5d4..4a9f392b69a23 100644 --- a/apps/studio/data/oauth/oauth-apps-query.ts +++ b/apps/studio/data/oauth/oauth-apps-query.ts @@ -29,11 +29,9 @@ export const useOAuthAppsQuery = ( { slug }: OAuthAppsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - oauthAppKeys.oauthApps(slug), - ({ signal }) => getOAuthApps({ slug }, signal), - { - enabled: enabled && typeof slug !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: oauthAppKeys.oauthApps(slug), + queryFn: ({ signal }) => getOAuthApps({ slug }, signal), + enabled: enabled && typeof slug !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/open-api/api-spec-query.ts b/apps/studio/data/open-api/api-spec-query.ts index 9bedd99f5e511..1fd001a9f3279 100644 --- a/apps/studio/data/open-api/api-spec-query.ts +++ b/apps/studio/data/open-api/api-spec-query.ts @@ -58,11 +58,9 @@ export const useOpenAPISpecQuery = ( { projectRef }: OpenAPISpecVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - openApiKeys.apiSpec(projectRef), - ({ signal }) => getOpenAPISpec({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: openApiKeys.apiSpec(projectRef), + queryFn: ({ signal }) => getOpenAPISpec({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/organization-members/organization-invitation-accept-mutation.ts b/apps/studio/data/organization-members/organization-invitation-accept-mutation.ts index f482b2ce09957..824c093343a5c 100644 --- a/apps/studio/data/organization-members/organization-invitation-accept-mutation.ts +++ b/apps/studio/data/organization-members/organization-invitation-accept-mutation.ts @@ -44,7 +44,8 @@ export const useOrganizationAcceptInvitationMutation = ({ OrganizationMemberUpdateData, ResponseError, OrganizationAcceptInvitationVariables - >((vars) => acceptOrganizationInvitation(vars), { + >({ + mutationFn: (vars) => acceptOrganizationInvitation(vars), async onSuccess(data, variables, context) { await invalidateOrganizationsQuery(queryClient) await invalidateProjectsQuery() diff --git a/apps/studio/data/organization-members/organization-invitation-create-mutation.ts b/apps/studio/data/organization-members/organization-invitation-create-mutation.ts index b7660ac0a5641..466ff6a6ac75f 100644 --- a/apps/studio/data/organization-members/organization-invitation-create-mutation.ts +++ b/apps/studio/data/organization-members/organization-invitation-create-mutation.ts @@ -52,7 +52,8 @@ export const useOrganizationCreateInvitationMutation = ({ OrganizationMemberUpdateData, ResponseError, OrganizationCreateInvitationVariables - >((vars) => createOrganizationInvitation(vars), { + >({ + mutationFn: (vars) => createOrganizationInvitation(vars), async onSuccess(data, variables, context) { const { slug } = variables diff --git a/apps/studio/data/organization-members/organization-invitation-delete-mutation.ts b/apps/studio/data/organization-members/organization-invitation-delete-mutation.ts index 7cb7da986bf50..19a0d9ed66426 100644 --- a/apps/studio/data/organization-members/organization-invitation-delete-mutation.ts +++ b/apps/studio/data/organization-members/organization-invitation-delete-mutation.ts @@ -44,7 +44,8 @@ export const useOrganizationDeleteInvitationMutation = ({ OrganizationDeleteInvitationData, ResponseError, OrganizationDeleteInvitationVariables - >((vars) => deleteOrganizationInvitation(vars), { + >({ + mutationFn: (vars) => deleteOrganizationInvitation(vars), async onSuccess(data, variables, context) { const { slug, skipInvalidation } = variables diff --git a/apps/studio/data/organization-members/organization-invitation-token-query.ts b/apps/studio/data/organization-members/organization-invitation-token-query.ts index 921c3d978b965..e65cc45b73e3c 100644 --- a/apps/studio/data/organization-members/organization-invitation-token-query.ts +++ b/apps/studio/data/organization-members/organization-invitation-token-query.ts @@ -35,12 +35,10 @@ export const useOrganizationInvitationTokenQuery = = {} ) => { - return useQuery( - organizationKeys.token(slug, token), - ({ signal }) => getOrganizationInviteByToken({ slug, token }, signal), - { - enabled: enabled && typeof slug !== 'undefined' && typeof token !== 'undefined', - ...options, - } - ) + return useQuery({ + queryKey: organizationKeys.token(slug, token), + queryFn: ({ signal }) => getOrganizationInviteByToken({ slug, token }, signal), + enabled: enabled && typeof slug !== 'undefined' && typeof token !== 'undefined', + ...options, + }) } diff --git a/apps/studio/data/organization-members/organization-member-role-assign-mutation.ts b/apps/studio/data/organization-members/organization-member-role-assign-mutation.ts index 3e7484c986b56..bde0fd9360858 100644 --- a/apps/studio/data/organization-members/organization-member-role-assign-mutation.ts +++ b/apps/studio/data/organization-members/organization-member-role-assign-mutation.ts @@ -54,7 +54,8 @@ export const useOrganizationMemberAssignRoleMutation = ({ OrganizationMemberAssignData, ResponseError, OrganizationMemberAssignRoleVariables - >((vars) => assignOrganizationMemberRole(vars), { + >({ + mutationFn: (vars) => assignOrganizationMemberRole(vars), async onSuccess(data, variables, context) { const { slug, skipInvalidation } = variables diff --git a/apps/studio/data/organization-members/organization-member-role-unassign-mutation.ts b/apps/studio/data/organization-members/organization-member-role-unassign-mutation.ts index c7d9060911830..58680b9457fef 100644 --- a/apps/studio/data/organization-members/organization-member-role-unassign-mutation.ts +++ b/apps/studio/data/organization-members/organization-member-role-unassign-mutation.ts @@ -55,7 +55,8 @@ export const useOrganizationMemberUnassignRoleMutation = ({ OrganizationMemberUnassignRoleData, ResponseError, OrganizationMemberUnassignRoleVariables - >((vars) => unassignOrganizationMemberRole(vars), { + >({ + mutationFn: (vars) => unassignOrganizationMemberRole(vars), async onSuccess(data, variables, context) { const { slug, skipInvalidation } = variables diff --git a/apps/studio/data/organization-members/organization-member-role-update-mutation.ts b/apps/studio/data/organization-members/organization-member-role-update-mutation.ts index 0866ae2d4ca51..a6939f982e900 100644 --- a/apps/studio/data/organization-members/organization-member-role-update-mutation.ts +++ b/apps/studio/data/organization-members/organization-member-role-update-mutation.ts @@ -54,7 +54,8 @@ export const useOrganizationMemberUpdateRoleMutation = ({ OrganizationMemberAssignData, ResponseError, OrganizationMemberUpdateRoleVariables - >((vars) => assignOrganizationMemberRole(vars), { + >({ + mutationFn: (vars) => assignOrganizationMemberRole(vars), async onSuccess(data, variables, context) { const { slug, skipInvalidation } = variables diff --git a/apps/studio/data/organization-members/organization-roles-query.ts b/apps/studio/data/organization-members/organization-roles-query.ts index 9a0be12bee757..1085ee8b73b68 100644 --- a/apps/studio/data/organization-members/organization-roles-query.ts +++ b/apps/studio/data/organization-members/organization-roles-query.ts @@ -36,19 +36,17 @@ export const useOrganizationRolesV2Query = ( ...options }: UseQueryOptions = {} ) => - useQuery( - organizationKeys.rolesV2(slug), - ({ signal }) => getOrganizationRoles({ slug }, signal), - { - enabled: enabled && typeof slug !== 'undefined', - select: (data) => { - return { - ...data, - org_scoped_roles: data.org_scoped_roles.sort((a, b) => { - return FIXED_ROLE_ORDER.indexOf(a.name) - FIXED_ROLE_ORDER.indexOf(b.name) - }), - } as any - }, - ...options, - } - ) + useQuery({ + queryKey: organizationKeys.rolesV2(slug), + queryFn: ({ signal }) => getOrganizationRoles({ slug }, signal), + enabled: enabled && typeof slug !== 'undefined', + select: (data) => { + return { + ...data, + org_scoped_roles: data.org_scoped_roles.sort((a, b) => { + return FIXED_ROLE_ORDER.indexOf(a.name) - FIXED_ROLE_ORDER.indexOf(b.name) + }), + } as any + }, + ...options, + }) diff --git a/apps/studio/data/organizations/free-project-limit-check-query.ts b/apps/studio/data/organizations/free-project-limit-check-query.ts index 63e4b89b79fc1..1b37ebb88335f 100644 --- a/apps/studio/data/organizations/free-project-limit-check-query.ts +++ b/apps/studio/data/organizations/free-project-limit-check-query.ts @@ -38,11 +38,9 @@ export const useFreeProjectLimitCheckQuery = ...options }: UseQueryOptions = {} ) => - useQuery( - organizationKeys.freeProjectLimitCheck(slug), - ({ signal }) => getFreeProjectLimitCheck({ slug }, signal), - { - enabled: enabled && typeof slug !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: organizationKeys.freeProjectLimitCheck(slug), + queryFn: ({ signal }) => getFreeProjectLimitCheck({ slug }, signal), + enabled: enabled && typeof slug !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/organizations/keys.ts b/apps/studio/data/organizations/keys.ts index 64dabc7a7f67a..28fb5e039afaf 100644 --- a/apps/studio/data/organizations/keys.ts +++ b/apps/studio/data/organizations/keys.ts @@ -1,5 +1,3 @@ -import type { DesiredInstanceSizeForAvailableRegions } from './organization-available-regions-query' - export const organizationKeys = { list: () => ['organizations'] as const, detail: (slug?: string) => ['organizations', slug] as const, @@ -22,9 +20,6 @@ export const organizationKeys = { ['organizations', slug, 'validate-token', token] as const, projectClaim: (slug: string, token: string) => ['organizations', slug, 'project-claim', token] as const, - availableRegions: ( - slug: string | undefined, - cloudProvider: string, - size?: DesiredInstanceSizeForAvailableRegions - ) => ['organizations', slug, 'available-regions', cloudProvider, size] as const, + availableRegions: (slug: string | undefined, cloudProvider: string, size?: string) => + ['organizations', slug, 'available-regions', cloudProvider, size] as const, } diff --git a/apps/studio/data/organizations/organization-audit-logs-query.ts b/apps/studio/data/organizations/organization-audit-logs-query.ts index 47f3cf7f37205..0be36991c7add 100644 --- a/apps/studio/data/organizations/organization-audit-logs-query.ts +++ b/apps/studio/data/organizations/organization-audit-logs-query.ts @@ -68,15 +68,13 @@ export const useOrganizationAuditLogsQuery = ) => { const { slug, iso_timestamp_start, iso_timestamp_end } = vars - return useQuery( - organizationKeys.auditLogs(slug, { + return useQuery({ + queryKey: organizationKeys.auditLogs(slug, { date_start: iso_timestamp_start, date_end: iso_timestamp_end, }), - ({ signal }) => getOrganizationAuditLogs(vars, signal), - { - enabled: enabled && typeof slug !== 'undefined', - ...options, - } - ) + queryFn: ({ signal }) => getOrganizationAuditLogs(vars, signal), + enabled: enabled && typeof slug !== 'undefined', + ...options, + }) } diff --git a/apps/studio/data/organizations/organization-billing-subscription-preview.ts b/apps/studio/data/organizations/organization-billing-subscription-preview.ts index beb079b520e2b..cf667a8b6f152 100644 --- a/apps/studio/data/organizations/organization-billing-subscription-preview.ts +++ b/apps/studio/data/organizations/organization-billing-subscription-preview.ts @@ -83,29 +83,26 @@ export const useOrganizationBillingSubscriptionPreview = < ...options }: UseQueryOptions = {} ) => - useQuery( - organizationKeys.subscriptionPreview(organizationSlug, tier), - () => previewOrganizationBillingSubscription({ organizationSlug, tier }), - { - enabled: enabled && typeof organizationSlug !== 'undefined' && typeof tier !== 'undefined', - ...options, - - retry: (failureCount, error) => { - // Don't retry on 400s - if ( - typeof error === 'object' && - error !== null && - 'code' in error && - (error as any).code === 400 - ) { - return false - } + useQuery({ + queryKey: organizationKeys.subscriptionPreview(organizationSlug, tier), + queryFn: () => previewOrganizationBillingSubscription({ organizationSlug, tier }), + enabled: enabled && typeof organizationSlug !== 'undefined' && typeof tier !== 'undefined', + ...options, + retry: (failureCount, error) => { + // Don't retry on 400s + if ( + typeof error === 'object' && + error !== null && + 'code' in error && + (error as any).code === 400 + ) { + return false + } - if (failureCount < 3) { - return true - } + if (failureCount < 3) { + return true + } - return false - }, - } - ) + return false + }, + }) diff --git a/apps/studio/data/organizations/organization-by-fly-organization-id-mutation.ts b/apps/studio/data/organizations/organization-by-fly-organization-id-mutation.ts index 94cd801beeb7c..4e015facf5eae 100644 --- a/apps/studio/data/organizations/organization-by-fly-organization-id-mutation.ts +++ b/apps/studio/data/organizations/organization-by-fly-organization-id-mutation.ts @@ -31,20 +31,18 @@ export const useOrganizationByFlyOrgIdMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => getOrganizationByFlyOrgId(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to get organization: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => getOrganizationByFlyOrgId(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to get organization: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/organizations/organization-create-mutation.ts b/apps/studio/data/organizations/organization-create-mutation.ts index 93024acbb3be4..657a91940c797 100644 --- a/apps/studio/data/organizations/organization-create-mutation.ts +++ b/apps/studio/data/organizations/organization-create-mutation.ts @@ -58,40 +58,38 @@ export const useOrganizationCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createOrganization(vars), - { - async onSuccess(data, variables, context) { - if (data && !('pending_payment_intent_secret' in data)) { - // [Joshen] We're manually updating the query client here as the org's subscription is - // created async, and the invalidation will happen too quick where the GET organizations - // endpoint will error out with a 500 since the subscription isn't created yet. - queryClient.setQueriesData( - { - queryKey: organizationKeys.list(), - exact: true, - }, - (prev: any) => { - if (!prev) return prev - return [...prev, castOrganizationResponseToOrganization(data)] - } - ) - - await queryClient.invalidateQueries(permissionKeys.list()) - } - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create organization: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createOrganization(vars), + async onSuccess(data, variables, context) { + if (data && !('pending_payment_intent_secret' in data)) { + // [Joshen] We're manually updating the query client here as the org's subscription is + // created async, and the invalidation will happen too quick where the GET organizations + // endpoint will error out with a 500 since the subscription isn't created yet. + queryClient.setQueriesData( + { + queryKey: organizationKeys.list(), + exact: true, + }, + (prev: any) => { + if (!prev) return prev + return [...prev, castOrganizationResponseToOrganization(data)] + } + ) + + await queryClient.invalidateQueries(permissionKeys.list()) + } + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create organization: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } export type AwsManagedOrganizationCreateVariables = { @@ -140,7 +138,8 @@ export const useAwsManagedOrganizationCreateMutation = ({ AwsManagedOrganizationCreateData, ResponseError, AwsManagedOrganizationCreateVariables - >((vars) => createAwsManagedOrganization(vars), { + >({ + mutationFn: (vars) => createAwsManagedOrganization(vars), async onSuccess(data, variables, context) { if (data) { // [Joshen] We're manually updating the query client here as the org's subscription is diff --git a/apps/studio/data/organizations/organization-credit-top-up-mutation.ts b/apps/studio/data/organizations/organization-credit-top-up-mutation.ts index f69aa24a0cf6f..7e8e984b3da06 100644 --- a/apps/studio/data/organizations/organization-credit-top-up-mutation.ts +++ b/apps/studio/data/organizations/organization-credit-top-up-mutation.ts @@ -67,20 +67,18 @@ export const useOrganizationCreditTopUpMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => topUpCredits(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to top up credits: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => topUpCredits(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to top up credits: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/organizations/organization-customer-profile-query.ts b/apps/studio/data/organizations/organization-customer-profile-query.ts index 1b6373605fb13..8545bba1794a5 100644 --- a/apps/studio/data/organizations/organization-customer-profile-query.ts +++ b/apps/studio/data/organizations/organization-customer-profile-query.ts @@ -49,12 +49,10 @@ export const useOrganizationCustomerProfileQuery = ( - organizationKeys.customerProfile(slug), - ({ signal }) => getOrganizationCustomerProfile({ slug }, signal), - { - enabled: IS_PLATFORM && enabled && canReadCustomerProfile && typeof slug !== 'undefined', - ...options, - } - ) + return useQuery({ + queryKey: organizationKeys.customerProfile(slug), + queryFn: ({ signal }) => getOrganizationCustomerProfile({ slug }, signal), + enabled: IS_PLATFORM && enabled && canReadCustomerProfile && typeof slug !== 'undefined', + ...options, + }) } diff --git a/apps/studio/data/organizations/organization-customer-profile-update-mutation.ts b/apps/studio/data/organizations/organization-customer-profile-update-mutation.ts index 1aa48d9ab9103..341d24f715868 100644 --- a/apps/studio/data/organizations/organization-customer-profile-update-mutation.ts +++ b/apps/studio/data/organizations/organization-customer-profile-update-mutation.ts @@ -56,7 +56,8 @@ export const useOrganizationCustomerProfileUpdateMutation = ({ OrganizationCustomerProfileUpdateData, ResponseError, OrganizationCustomerProfileUpdateVariables - >((vars) => updateOrganizationCustomerProfile(vars), { + >({ + mutationFn: (vars) => updateOrganizationCustomerProfile(vars), async onSuccess(data, variables, context) { const { address, slug, billing_name } = variables diff --git a/apps/studio/data/organizations/organization-delete-mutation.ts b/apps/studio/data/organizations/organization-delete-mutation.ts index 07c5f19e6340a..f4460804521eb 100644 --- a/apps/studio/data/organizations/organization-delete-mutation.ts +++ b/apps/studio/data/organizations/organization-delete-mutation.ts @@ -30,24 +30,22 @@ export const useOrganizationDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteOrganization(vars), - { - async onSuccess(data, variables, context) { - await Promise.all([ - queryClient.invalidateQueries(organizationKeys.list()), - queryClient.invalidateQueries(permissionKeys.list()), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete organization: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteOrganization(vars), + async onSuccess(data, variables, context) { + await Promise.all([ + queryClient.invalidateQueries(organizationKeys.list()), + queryClient.invalidateQueries(permissionKeys.list()), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete organization: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/organizations/organization-link-aws-marketplace-mutation.ts b/apps/studio/data/organizations/organization-link-aws-marketplace-mutation.ts index a8ac033a76499..829ae1c243203 100644 --- a/apps/studio/data/organizations/organization-link-aws-marketplace-mutation.ts +++ b/apps/studio/data/organizations/organization-link-aws-marketplace-mutation.ts @@ -32,20 +32,18 @@ export const useOrganizationLinkAwsMarketplaceMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => linkOrganization(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to link organization to AWS Marketplace: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => linkOrganization(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to link organization to AWS Marketplace: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/organizations/organization-member-delete-mutation.ts b/apps/studio/data/organizations/organization-member-delete-mutation.ts index 1f9e013908eeb..8b9b05c3f33f7 100644 --- a/apps/studio/data/organizations/organization-member-delete-mutation.ts +++ b/apps/studio/data/organizations/organization-member-delete-mutation.ts @@ -41,7 +41,8 @@ export const useOrganizationMemberDeleteMutation = ({ OrganizationMemberDeleteData, ResponseError, OrganizationMemberDeleteVariables - >((vars) => deleteOrganizationMember(vars), { + >({ + mutationFn: (vars) => deleteOrganizationMember(vars), async onSuccess(data, variables, context) { const { slug } = variables diff --git a/apps/studio/data/organizations/organization-members-query.ts b/apps/studio/data/organizations/organization-members-query.ts index c4c0c80174535..444c3580ee26b 100644 --- a/apps/studio/data/organizations/organization-members-query.ts +++ b/apps/studio/data/organizations/organization-members-query.ts @@ -60,11 +60,9 @@ export const useOrganizationMembersQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - organizationKeys.members(slug), - ({ signal }) => getOrganizationMembers({ slug }, signal), - { - enabled: enabled && typeof slug !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: organizationKeys.members(slug), + queryFn: ({ signal }) => getOrganizationMembers({ slug }, signal), + enabled: enabled && typeof slug !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/organizations/organization-mfa-mutation.ts b/apps/studio/data/organizations/organization-mfa-mutation.ts index 483d804d63974..b0e964d6a7faa 100644 --- a/apps/studio/data/organizations/organization-mfa-mutation.ts +++ b/apps/studio/data/organizations/organization-mfa-mutation.ts @@ -34,24 +34,22 @@ export const useOrganizationMfaToggleMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => toggleOrganizationMfa(vars), - { - async onSuccess(data, variables, context) { - const { slug } = variables + return useMutation({ + mutationFn: (vars) => toggleOrganizationMfa(vars), + async onSuccess(data, variables, context) { + const { slug } = variables - // We already have the data, no need to refetch - queryClient.setQueryData(organizationKeys.mfa(slug), data.enforced) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update MFA enforcement: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + // We already have the data, no need to refetch + queryClient.setQueryData(organizationKeys.mfa(slug), data.enforced) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update MFA enforcement: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/organizations/organization-mfa-query.ts b/apps/studio/data/organizations/organization-mfa-query.ts index fc608a431c8ce..0105816198e4d 100644 --- a/apps/studio/data/organizations/organization-mfa-query.ts +++ b/apps/studio/data/organizations/organization-mfa-query.ts @@ -31,11 +31,9 @@ export const useOrganizationMfaQuery = ( { slug }: OrganizationMfaVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - organizationKeys.mfa(slug), - ({ signal }) => getOrganizationMfaEnforcement({ slug }, signal), - { - enabled: enabled && typeof slug !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: organizationKeys.mfa(slug), + queryFn: ({ signal }) => getOrganizationMfaEnforcement({ slug }, signal), + enabled: enabled && typeof slug !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/organizations/organization-payment-method-default-mutation.ts b/apps/studio/data/organizations/organization-payment-method-default-mutation.ts index 998346a410806..145088ae520f4 100644 --- a/apps/studio/data/organizations/organization-payment-method-default-mutation.ts +++ b/apps/studio/data/organizations/organization-payment-method-default-mutation.ts @@ -47,7 +47,8 @@ export const useOrganizationPaymentMethodMarkAsDefaultMutation = ({ OrganizationPaymentMethodDefaultData, ResponseError, OrganizationPaymentMethodDefaultVariables - >((vars) => markPaymentMethodAsDefault(vars), { + >({ + mutationFn: (vars) => markPaymentMethodAsDefault(vars), async onSuccess(data, variables, context) { const { slug, paymentMethodId } = variables // We do not invalidate payment methods here as endpoint data is stale for 1-2 seconds, so we handle state manually diff --git a/apps/studio/data/organizations/organization-payment-method-delete-mutation.ts b/apps/studio/data/organizations/organization-payment-method-delete-mutation.ts index 754f0c3044d05..12dd4d6f33a6e 100644 --- a/apps/studio/data/organizations/organization-payment-method-delete-mutation.ts +++ b/apps/studio/data/organizations/organization-payment-method-delete-mutation.ts @@ -48,7 +48,8 @@ export const useOrganizationPaymentMethodDeleteMutation = ({ OrganizationPaymentMethodDeleteData, ResponseError, OrganizationPaymentMethodDeleteVariables - >((vars) => deletePaymentMethod(vars), { + >({ + mutationFn: (vars) => deletePaymentMethod(vars), async onSuccess(data, variables, context) { const { slug } = variables await queryClient.invalidateQueries(organizationKeys.paymentMethods(slug)) diff --git a/apps/studio/data/organizations/organization-payment-method-setup-intent-mutation.ts b/apps/studio/data/organizations/organization-payment-method-setup-intent-mutation.ts index 2901a12c837f0..044ef993f3c40 100644 --- a/apps/studio/data/organizations/organization-payment-method-setup-intent-mutation.ts +++ b/apps/studio/data/organizations/organization-payment-method-setup-intent-mutation.ts @@ -41,7 +41,8 @@ export const useOrganizationPaymentMethodSetupIntent = ({ OrganizationPaymentMethodSetupIntentData, ResponseError, OrganizationPaymentMethodSetupIntentVariables - >((vars) => setupPaymentMethodIntent(vars), { + >({ + mutationFn: (vars) => setupPaymentMethodIntent(vars), async onSuccess(data, variables, context) { await onSuccess?.(data, variables, context) }, diff --git a/apps/studio/data/organizations/organization-payment-methods-query.ts b/apps/studio/data/organizations/organization-payment-methods-query.ts index cc22ddd36c5b7..a2571a3ddb264 100644 --- a/apps/studio/data/organizations/organization-payment-methods-query.ts +++ b/apps/studio/data/organizations/organization-payment-methods-query.ts @@ -48,9 +48,10 @@ export const useOrganizationPaymentMethodsQuery = ( - organizationKeys.paymentMethods(slug), - ({ signal }) => getOrganizationPaymentMethods({ slug }, signal), - { enabled: enabled && typeof slug !== 'undefined' && canReadSubscriptions, ...options } - ) + return useQuery({ + queryKey: organizationKeys.paymentMethods(slug), + queryFn: ({ signal }) => getOrganizationPaymentMethods({ slug }, signal), + enabled: enabled && typeof slug !== 'undefined' && canReadSubscriptions, + ...options, + }) } diff --git a/apps/studio/data/organizations/organization-project-claim-mutation.ts b/apps/studio/data/organizations/organization-project-claim-mutation.ts index 16d42a3157170..9a3e7223e8109 100644 --- a/apps/studio/data/organizations/organization-project-claim-mutation.ts +++ b/apps/studio/data/organizations/organization-project-claim-mutation.ts @@ -35,7 +35,8 @@ export const useOrganizationProjectClaimMutation = ({ ClaimOrganizationProjectData, ResponseError, OrganizationProjectClaimVariables - >((vars) => claimOrganizationProject(vars), { + >({ + mutationFn: (vars) => claimOrganizationProject(vars), async onSuccess(data, variables, context) { await onSuccess?.(data, variables, context) }, diff --git a/apps/studio/data/organizations/organization-project-claim-query.ts b/apps/studio/data/organizations/organization-project-claim-query.ts index 169043d7fdcd8..c8abadb23bd3f 100644 --- a/apps/studio/data/organizations/organization-project-claim-query.ts +++ b/apps/studio/data/organizations/organization-project-claim-query.ts @@ -69,8 +69,8 @@ export const useOrganizationProjectClaimQuery = = {} ) => - useQuery( - organizationKeys.projectClaim(slug, token), - ({ signal }) => getOrganizationProjectClaim({ slug, token }, signal), - { ...options } - ) + useQuery({ + queryKey: organizationKeys.projectClaim(slug, token), + queryFn: ({ signal }) => getOrganizationProjectClaim({ slug, token }, signal), + ...options, + }) diff --git a/apps/studio/data/organizations/organization-query.ts b/apps/studio/data/organizations/organization-query.ts index 2ee9543f5bed3..fe46fab867624 100644 --- a/apps/studio/data/organizations/organization-query.ts +++ b/apps/studio/data/organizations/organization-query.ts @@ -37,11 +37,13 @@ export const useOrganizationQuery = ( { slug }: OrganizationVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => { - return useQuery( - organizationKeys.detail(slug), - ({ signal }) => getOrganization({ slug }, signal), - { enabled: enabled && typeof slug !== 'undefined', ...options, staleTime: 30 * 60 * 1000 } - ) + return useQuery({ + queryKey: organizationKeys.detail(slug), + queryFn: ({ signal }) => getOrganization({ slug }, signal), + enabled: enabled && typeof slug !== 'undefined', + ...options, + staleTime: 30 * 60 * 1000, + }) } export function invalidateOrganizationsQuery(client: QueryClient) { diff --git a/apps/studio/data/organizations/organization-tax-id-query.ts b/apps/studio/data/organizations/organization-tax-id-query.ts index ede1efe0c2f0c..fe4ea3ab0a3a9 100644 --- a/apps/studio/data/organizations/organization-tax-id-query.ts +++ b/apps/studio/data/organizations/organization-tax-id-query.ts @@ -41,12 +41,10 @@ export const useOrganizationTaxIdQuery = ( 'stripe.tax_ids' ) - return useQuery( - organizationKeys.taxId(slug), - ({ signal }) => getOrganizationTaxId({ slug }, signal), - { - enabled: enabled && typeof slug !== 'undefined' && canReadSubscriptions, - ...options, - } - ) + return useQuery({ + queryKey: organizationKeys.taxId(slug), + queryFn: ({ signal }) => getOrganizationTaxId({ slug }, signal), + enabled: enabled && typeof slug !== 'undefined' && canReadSubscriptions, + ...options, + }) } diff --git a/apps/studio/data/organizations/organization-tax-id-update-mutation.ts b/apps/studio/data/organizations/organization-tax-id-update-mutation.ts index 14bec45b56470..2feea64e7d464 100644 --- a/apps/studio/data/organizations/organization-tax-id-update-mutation.ts +++ b/apps/studio/data/organizations/organization-tax-id-update-mutation.ts @@ -59,24 +59,22 @@ export const useOrganizationTaxIdUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateOrganizationTaxId(vars), - { - async onSuccess(data, variables, context) { - const { slug } = variables + return useMutation({ + mutationFn: (vars) => updateOrganizationTaxId(vars), + async onSuccess(data, variables, context) { + const { slug } = variables - // We already have the data, no need to refetch - queryClient.setQueryData(organizationKeys.taxId(slug), data.tax_id) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update tax id: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + // We already have the data, no need to refetch + queryClient.setQueryData(organizationKeys.taxId(slug), data.tax_id) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update tax id: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/organizations/organization-update-mutation.ts b/apps/studio/data/organizations/organization-update-mutation.ts index 81883ba76263a..81a22616fd3b4 100644 --- a/apps/studio/data/organizations/organization-update-mutation.ts +++ b/apps/studio/data/organizations/organization-update-mutation.ts @@ -49,71 +49,69 @@ export const useOrganizationUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateOrganization(vars), - { - async onSuccess(data, variables, context) { - queryClient.setQueriesData( - { - queryKey: organizationKeys.list(), - exact: true, - }, - (prev: components['schemas']['OrganizationResponse'][] | undefined) => { - if (!prev) return prev + return useMutation({ + mutationFn: (vars) => updateOrganization(vars), + async onSuccess(data, variables, context) { + queryClient.setQueriesData( + { + queryKey: organizationKeys.list(), + exact: true, + }, + (prev: components['schemas']['OrganizationResponse'][] | undefined) => { + if (!prev) return prev - return prev.map((org) => { - if (org.slug !== variables.slug) return org + return prev.map((org) => { + if (org.slug !== variables.slug) return org - return { - ...org, - name: variables.name || org.name, - billing_email: variables.billing_email || org.billing_email, - opt_in_tags: variables.opt_in_tags || org.opt_in_tags, - } - }) - } - ) - - queryClient.setQueriesData( - { - queryKey: organizationKeys.customerProfile(data.slug), - exact: true, - }, - (prev: components['schemas']['CustomerResponse'] | undefined) => { - if (!prev) return prev return { - ...prev, - additional_emails: variables.additional_billing_emails || prev.additional_emails, + ...org, + name: variables.name || org.name, + billing_email: variables.billing_email || org.billing_email, + opt_in_tags: variables.opt_in_tags || org.opt_in_tags, } - } - ) + }) + } + ) - queryClient.setQueriesData( - { - queryKey: organizationKeys.detail(data.slug), - exact: true, - }, - (prev: components['schemas']['OrganizationSlugResponse'] | undefined) => { - if (!prev) return prev - return { - ...prev, - name: variables.name || prev.name, - billing_email: variables.billing_email || prev.billing_email, - opt_in_tags: variables.opt_in_tags || prev.opt_in_tags, - } + queryClient.setQueriesData( + { + queryKey: organizationKeys.customerProfile(data.slug), + exact: true, + }, + (prev: components['schemas']['CustomerResponse'] | undefined) => { + if (!prev) return prev + return { + ...prev, + additional_emails: variables.additional_billing_emails || prev.additional_emails, } - ) + } + ) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update organization: ${data.message}`) - } else { - onError(data, variables, context) + queryClient.setQueriesData( + { + queryKey: organizationKeys.detail(data.slug), + exact: true, + }, + (prev: components['schemas']['OrganizationSlugResponse'] | undefined) => { + if (!prev) return prev + return { + ...prev, + name: variables.name || prev.name, + billing_email: variables.billing_email || prev.billing_email, + opt_in_tags: variables.opt_in_tags || prev.opt_in_tags, + } } - }, - ...options, - } - ) + ) + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update organization: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/organizations/organizations-query.ts b/apps/studio/data/organizations/organizations-query.ts index 449a41c1206bc..d4948d3bfef35 100644 --- a/apps/studio/data/organizations/organizations-query.ts +++ b/apps/studio/data/organizations/organizations-query.ts @@ -54,11 +54,13 @@ export const useOrganizationsQuery = ({ ...options }: UseQueryOptions = {}) => { const { profile } = useProfile() - return useQuery( - organizationKeys.list(), - ({ signal }) => getOrganizations({ signal }), - { enabled: enabled && profile !== undefined, ...options, staleTime: 30 * 60 * 1000 } - ) + return useQuery({ + queryKey: organizationKeys.list(), + queryFn: ({ signal }) => getOrganizations({ signal }), + enabled: enabled && profile !== undefined, + ...options, + staleTime: 30 * 60 * 1000, + }) } export function invalidateOrganizationsQuery(client: QueryClient) { diff --git a/apps/studio/data/permissions/permissions-query.ts b/apps/studio/data/permissions/permissions-query.ts index 5de599ed44bd8..875a823ee5a96 100644 --- a/apps/studio/data/permissions/permissions-query.ts +++ b/apps/studio/data/permissions/permissions-query.ts @@ -36,13 +36,11 @@ export const usePermissionsQuery = ({ }: UseQueryOptions = {}) => { const isLoggedIn = useIsLoggedIn() - return useQuery( - permissionKeys.list(), - ({ signal }) => getPermissions(signal), - { - ...options, - enabled: IS_PLATFORM && enabled && isLoggedIn, - staleTime: 5 * 60 * 1000, - } - ) + return useQuery({ + queryKey: permissionKeys.list(), + queryFn: ({ signal }) => getPermissions(signal), + ...options, + enabled: IS_PLATFORM && enabled && isLoggedIn, + staleTime: 5 * 60 * 1000, + }) } diff --git a/apps/studio/data/platform/platform-status-query.ts b/apps/studio/data/platform/platform-status-query.ts index 6578e2cda9fff..fb92d2e154f9c 100644 --- a/apps/studio/data/platform/platform-status-query.ts +++ b/apps/studio/data/platform/platform-status-query.ts @@ -19,8 +19,8 @@ export type PlatformStatusError = unknown export const usePlatformStatusQuery = ( options: UseQueryOptions = {} ) => - useQuery( - platformKeys.status(), - ({ signal }) => getPlatformStatus(signal), - options - ) + useQuery({ + queryKey: platformKeys.status(), + queryFn: ({ signal }) => getPlatformStatus(signal), + ...options, + }) diff --git a/apps/studio/data/privileges/column-privileges-grant-mutation.ts b/apps/studio/data/privileges/column-privileges-grant-mutation.ts index e1e6933c59323..6452d45b52bb8 100644 --- a/apps/studio/data/privileges/column-privileges-grant-mutation.ts +++ b/apps/studio/data/privileges/column-privileges-grant-mutation.ts @@ -50,26 +50,24 @@ export const useColumnPrivilegesGrantMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => grantColumnPrivileges(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables + return useMutation({ + mutationFn: (vars) => grantColumnPrivileges(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables - await Promise.all([ - queryClient.invalidateQueries(privilegeKeys.columnPrivilegesList(projectRef)), - ]) + await Promise.all([ + queryClient.invalidateQueries(privilegeKeys.columnPrivilegesList(projectRef)), + ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to mutate: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to mutate: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/privileges/column-privileges-query.ts b/apps/studio/data/privileges/column-privileges-query.ts index 249a7c028ffb6..b9d3d866778ba 100644 --- a/apps/studio/data/privileges/column-privileges-query.ts +++ b/apps/studio/data/privileges/column-privileges-query.ts @@ -49,11 +49,9 @@ export const useColumnPrivilegesQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - privilegeKeys.columnPrivilegesList(projectRef), - ({ signal }) => getColumnPrivileges({ projectRef, connectionString }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: privilegeKeys.columnPrivilegesList(projectRef), + queryFn: ({ signal }) => getColumnPrivileges({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/privileges/column-privileges-revoke-mutation.ts b/apps/studio/data/privileges/column-privileges-revoke-mutation.ts index 2a0d94043ce50..5aa6a10c76193 100644 --- a/apps/studio/data/privileges/column-privileges-revoke-mutation.ts +++ b/apps/studio/data/privileges/column-privileges-revoke-mutation.ts @@ -49,26 +49,24 @@ export const useColumnPrivilegesRevokeMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => revokeColumnPrivileges(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables + return useMutation({ + mutationFn: (vars) => revokeColumnPrivileges(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables - await Promise.all([ - queryClient.invalidateQueries(privilegeKeys.columnPrivilegesList(projectRef)), - ]) + await Promise.all([ + queryClient.invalidateQueries(privilegeKeys.columnPrivilegesList(projectRef)), + ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to mutate: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to mutate: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/privileges/table-privileges-grant-mutation.ts b/apps/studio/data/privileges/table-privileges-grant-mutation.ts index 82cb40f312c3a..a9892062bbacf 100644 --- a/apps/studio/data/privileges/table-privileges-grant-mutation.ts +++ b/apps/studio/data/privileges/table-privileges-grant-mutation.ts @@ -46,27 +46,25 @@ export const useTablePrivilegesGrantMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => grantTablePrivileges(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables + return useMutation({ + mutationFn: (vars) => grantTablePrivileges(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables - await Promise.all([ - invalidateTablePrivilegesQuery(queryClient, projectRef), - queryClient.invalidateQueries(privilegeKeys.columnPrivilegesList(projectRef)), - ]) + await Promise.all([ + invalidateTablePrivilegesQuery(queryClient, projectRef), + queryClient.invalidateQueries(privilegeKeys.columnPrivilegesList(projectRef)), + ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to mutate: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to mutate: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/privileges/table-privileges-query.ts b/apps/studio/data/privileges/table-privileges-query.ts index 5d31cb4929c64..9d872e654360b 100644 --- a/apps/studio/data/privileges/table-privileges-query.ts +++ b/apps/studio/data/privileges/table-privileges-query.ts @@ -41,14 +41,12 @@ export const useTablePrivilegesQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - privilegeKeys.tablePrivilegesList(projectRef), - ({ signal }) => getTablePrivileges({ projectRef, connectionString }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: privilegeKeys.tablePrivilegesList(projectRef), + queryFn: ({ signal }) => getTablePrivileges({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) export function invalidateTablePrivilegesQuery( client: QueryClient, diff --git a/apps/studio/data/privileges/table-privileges-revoke-mutation.ts b/apps/studio/data/privileges/table-privileges-revoke-mutation.ts index d9ffb39e2027e..eee996e3c8b29 100644 --- a/apps/studio/data/privileges/table-privileges-revoke-mutation.ts +++ b/apps/studio/data/privileges/table-privileges-revoke-mutation.ts @@ -46,27 +46,25 @@ export const useTablePrivilegesRevokeMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => revokeTablePrivileges(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables + return useMutation({ + mutationFn: (vars) => revokeTablePrivileges(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables - await Promise.all([ - invalidateTablePrivilegesQuery(queryClient, projectRef), - queryClient.invalidateQueries(privilegeKeys.columnPrivilegesList(projectRef)), - ]) + await Promise.all([ + invalidateTablePrivilegesQuery(queryClient, projectRef), + queryClient.invalidateQueries(privilegeKeys.columnPrivilegesList(projectRef)), + ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to mutate: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to mutate: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/profile/mfa-authenticator-assurance-level-query.ts b/apps/studio/data/profile/mfa-authenticator-assurance-level-query.ts index ad093941f40a7..ec2f78ca863e9 100644 --- a/apps/studio/data/profile/mfa-authenticator-assurance-level-query.ts +++ b/apps/studio/data/profile/mfa-authenticator-assurance-level-query.ts @@ -34,8 +34,10 @@ export const useAuthenticatorAssuranceLevelQuery = < CustomAuthMFAGetAuthenticatorAssuranceLevelData, CustomAuthMFAGetAuthenticatorAssuranceLevelError, TData - >(profileKeys.aaLevel(), () => getMfaAuthenticatorAssuranceLevel(), { - staleTime: 1000 * 60 * 30, // default good for 30 mins + >({ + queryKey: profileKeys.aaLevel(), + queryFn: () => getMfaAuthenticatorAssuranceLevel(), + staleTime: 1000 * 60 * 30, ...options, }) } diff --git a/apps/studio/data/profile/mfa-challenge-and-verify-mutation.ts b/apps/studio/data/profile/mfa-challenge-and-verify-mutation.ts index b70a7e5ab9e7f..556189898f2ed 100644 --- a/apps/studio/data/profile/mfa-challenge-and-verify-mutation.ts +++ b/apps/studio/data/profile/mfa-challenge-and-verify-mutation.ts @@ -31,34 +31,32 @@ export const useMfaChallengeAndVerifyMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => { + return useMutation({ + mutationFn: (vars) => { const { refreshFactors, ...params } = vars return mfaChallengeAndVerify(params) }, - { - async onSuccess(data, variables, context) { - // when a MFA is added, the aaLevel is bumped up - const refreshFactors = variables.refreshFactors ?? true + async onSuccess(data, variables, context) { + // when a MFA is added, the aaLevel is bumped up + const refreshFactors = variables.refreshFactors ?? true - await Promise.all([ - ...(refreshFactors ? [queryClient.invalidateQueries(profileKeys.mfaFactors())] : []), - queryClient.invalidateQueries(profileKeys.aaLevel()), - ]) + await Promise.all([ + ...(refreshFactors ? [queryClient.invalidateQueries(profileKeys.mfaFactors())] : []), + queryClient.invalidateQueries(profileKeys.aaLevel()), + ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to sign in: ${data.message}`) - } else { - onError(data, variables, context) - } - if (!WHITELIST_ERRORS.some((error) => data.message.includes(error))) { - Sentry.captureMessage('[CRITICAL] Failed to sign in via MFA: ' + data.message) - } - }, - ...options, - } - ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to sign in: ${data.message}`) + } else { + onError(data, variables, context) + } + if (!WHITELIST_ERRORS.some((error) => data.message.includes(error))) { + Sentry.captureMessage('[CRITICAL] Failed to sign in via MFA: ' + data.message) + } + }, + ...options, + }) } diff --git a/apps/studio/data/profile/mfa-enroll-mutation.ts b/apps/studio/data/profile/mfa-enroll-mutation.ts index f8ffe96020ba4..220974b50a2ca 100644 --- a/apps/studio/data/profile/mfa-enroll-mutation.ts +++ b/apps/studio/data/profile/mfa-enroll-mutation.ts @@ -21,7 +21,8 @@ export const useMfaEnrollMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation((vars) => mfaEnroll(vars), { + return useMutation({ + mutationFn: (vars) => mfaEnroll(vars), async onSuccess(data, variables, context) { await onSuccess?.(data, variables, context) }, diff --git a/apps/studio/data/profile/mfa-list-factors-query.ts b/apps/studio/data/profile/mfa-list-factors-query.ts index a4a7f9ae8c4f0..6e3ade9fd05f3 100644 --- a/apps/studio/data/profile/mfa-list-factors-query.ts +++ b/apps/studio/data/profile/mfa-list-factors-query.ts @@ -18,12 +18,10 @@ export const useMfaListFactorsQuery = ({ enabled = true, ...options }: UseQueryOptions = {}) => { - return useQuery( - profileKeys.mfaFactors(), - () => getMfaListFactors(), - { - staleTime: 1000 * 60 * 30, // default good for 30 mins - ...options, - } - ) + return useQuery({ + queryKey: profileKeys.mfaFactors(), + queryFn: () => getMfaListFactors(), + staleTime: 1000 * 60 * 30, + ...options, + }) } diff --git a/apps/studio/data/profile/mfa-unenroll-mutation.ts b/apps/studio/data/profile/mfa-unenroll-mutation.ts index 4b88df07476d2..5b6aa5288b672 100644 --- a/apps/studio/data/profile/mfa-unenroll-mutation.ts +++ b/apps/studio/data/profile/mfa-unenroll-mutation.ts @@ -24,7 +24,8 @@ export const useMfaUnenrollMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation((vars) => mfaUnenroll(vars), { + return useMutation({ + mutationFn: (vars) => mfaUnenroll(vars), async onSuccess(data, variables, context) { // when a factor is unenrolled, the aaLevel is bumped down if it's the last factor await Promise.all([ diff --git a/apps/studio/data/profile/profile-audit-logs-query.ts b/apps/studio/data/profile/profile-audit-logs-query.ts index 241933fe19567..209179d2fd1a2 100644 --- a/apps/studio/data/profile/profile-audit-logs-query.ts +++ b/apps/studio/data/profile/profile-audit-logs-query.ts @@ -40,12 +40,13 @@ export const useProfileAuditLogsQuery = ( options: UseQueryOptions = {} ) => { const { iso_timestamp_start, iso_timestamp_end } = vars - return useQuery( - profileKeys.auditLogs({ date_start: iso_timestamp_start, date_end: iso_timestamp_end }), - ({ signal }) => getProfileAuditLogs(vars, signal), - { - enabled: IS_PLATFORM && options.enabled, - ...options, - } - ) + return useQuery({ + queryKey: profileKeys.auditLogs({ + date_start: iso_timestamp_start, + date_end: iso_timestamp_end, + }), + queryFn: ({ signal }) => getProfileAuditLogs(vars, signal), + enabled: IS_PLATFORM && options.enabled, + ...options, + }) } diff --git a/apps/studio/data/profile/profile-create-mutation.ts b/apps/studio/data/profile/profile-create-mutation.ts index 0b373597a9f9c..48e296baed3f2 100644 --- a/apps/studio/data/profile/profile-create-mutation.ts +++ b/apps/studio/data/profile/profile-create-mutation.ts @@ -26,7 +26,8 @@ export const useProfileCreateMutation = ({ }: Omit, 'mutationFn'> = {}) => { const queryClient = useQueryClient() - return useMutation(() => createProfile(), { + return useMutation({ + mutationFn: () => createProfile(), async onSuccess(data, variables, context) { await Promise.all([ queryClient.invalidateQueries(profileKeys.profile()), diff --git a/apps/studio/data/profile/profile-identities-query.ts b/apps/studio/data/profile/profile-identities-query.ts index 15482f0536e0b..52cc46db893dc 100644 --- a/apps/studio/data/profile/profile-identities-query.ts +++ b/apps/studio/data/profile/profile-identities-query.ts @@ -29,9 +29,9 @@ export const useProfileIdentitiesQuery = ({ enabled = true, ...options }: UseQueryOptions = {}) => { - return useQuery( - profileKeys.identities(), - () => getProfileIdentities(), - { ...options } - ) + return useQuery({ + queryKey: profileKeys.identities(), + queryFn: () => getProfileIdentities(), + ...options, + }) } diff --git a/apps/studio/data/profile/profile-query.ts b/apps/studio/data/profile/profile-query.ts index 24b4df8870658..86b50d7ffb69b 100644 --- a/apps/studio/data/profile/profile-query.ts +++ b/apps/studio/data/profile/profile-query.ts @@ -31,13 +31,11 @@ export const useProfileQuery = ({ enabled = true, ...options }: UseQueryOptions = {}) => { - return useQuery( - profileKeys.profile(), - ({ signal }) => getProfile(signal), - { - staleTime: 1000 * 60 * 30, // default good for 30 mins - ...options, - enabled, - } - ) + return useQuery({ + queryKey: profileKeys.profile(), + queryFn: ({ signal }) => getProfile(signal), + staleTime: 1000 * 60 * 30, + ...options, + enabled, + }) } diff --git a/apps/studio/data/profile/profile-unlink-identity-mutation.ts b/apps/studio/data/profile/profile-unlink-identity-mutation.ts index 846be9b2fd235..50653e0543b70 100644 --- a/apps/studio/data/profile/profile-unlink-identity-mutation.ts +++ b/apps/studio/data/profile/profile-unlink-identity-mutation.ts @@ -24,7 +24,8 @@ export const useUnlinkIdentityMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation((vars) => unlinkIdentity(vars), { + return useMutation({ + mutationFn: (vars) => unlinkIdentity(vars), async onSuccess(data, variables, context) { await Promise.all([ auth.refreshSession(), diff --git a/apps/studio/data/profile/profile-update-email-mutation.ts b/apps/studio/data/profile/profile-update-email-mutation.ts index 3319ad4d33a5c..02437e37ef536 100644 --- a/apps/studio/data/profile/profile-update-email-mutation.ts +++ b/apps/studio/data/profile/profile-update-email-mutation.ts @@ -32,24 +32,22 @@ export const useEmailUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateEmail(vars), - { - async onSuccess(data, variables, context) { - await Promise.all([ - auth.refreshSession(), - queryClient.invalidateQueries(profileKeys.profile()), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update email: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateEmail(vars), + async onSuccess(data, variables, context) { + await Promise.all([ + auth.refreshSession(), + queryClient.invalidateQueries(profileKeys.profile()), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update email: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/profile/profile-update-mutation.ts b/apps/studio/data/profile/profile-update-mutation.ts index d86aac70a8bac..5a4cf41227da9 100644 --- a/apps/studio/data/profile/profile-update-mutation.ts +++ b/apps/studio/data/profile/profile-update-mutation.ts @@ -43,21 +43,19 @@ export const useProfileUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateProfile(vars), - { - async onSuccess(data, variables, context) { - await queryClient.invalidateQueries(profileKeys.profile()) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create profile: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateProfile(vars), + async onSuccess(data, variables, context) { + await queryClient.invalidateQueries(profileKeys.profile()) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create profile: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/projects/clone-mutation.ts b/apps/studio/data/projects/clone-mutation.ts index 7c7cec6772db5..e41daff40de3c 100644 --- a/apps/studio/data/projects/clone-mutation.ts +++ b/apps/studio/data/projects/clone-mutation.ts @@ -47,24 +47,22 @@ export const useProjectCloneMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => triggerClone(vars), - { - async onSuccess(data, variables, context) { - await queryClient.invalidateQueries({ - queryKey: projectKeys.listCloneBackups(variables.projectRef), - }) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - console.error(data) - toast.error(`Failed to trigger clone: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => triggerClone(vars), + async onSuccess(data, variables, context) { + await queryClient.invalidateQueries({ + queryKey: projectKeys.listCloneBackups(variables.projectRef), + }) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + console.error(data) + toast.error(`Failed to trigger clone: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/projects/clone-query.ts b/apps/studio/data/projects/clone-query.ts index 21b3df0adb828..11a18edf970b6 100644 --- a/apps/studio/data/projects/clone-query.ts +++ b/apps/studio/data/projects/clone-query.ts @@ -27,9 +27,10 @@ export const useCloneBackupsQuery = < { projectRef }: { projectRef?: string }, options: UseQueryOptions = {} ) => { - return useQuery( - projectKeys.listCloneBackups(projectRef), - () => getCloneBackups(projectRef), - { enabled: !!projectRef, ...options } - ) + return useQuery({ + queryKey: projectKeys.listCloneBackups(projectRef), + queryFn: () => getCloneBackups(projectRef), + enabled: !!projectRef, + ...options, + }) } diff --git a/apps/studio/data/projects/clone-status-query.ts b/apps/studio/data/projects/clone-status-query.ts index 6a85892d1388f..71b816badcf23 100644 --- a/apps/studio/data/projects/clone-status-query.ts +++ b/apps/studio/data/projects/clone-status-query.ts @@ -24,9 +24,10 @@ export const useCloneStatusQuery = ( { projectRef }: { projectRef?: string }, options: UseQueryOptions = {} ) => { - return useQuery( - projectKeys.listCloneStatus(projectRef), - () => getCloneStatus(projectRef), - { enabled: !!projectRef, ...options } - ) + return useQuery({ + queryKey: projectKeys.listCloneStatus(projectRef), + queryFn: () => getCloneStatus(projectRef), + enabled: !!projectRef, + ...options, + }) } diff --git a/apps/studio/data/projects/project-by-fly-extension-id-mutation.ts b/apps/studio/data/projects/project-by-fly-extension-id-mutation.ts index efbd08546c15c..b3cb3cca45e47 100644 --- a/apps/studio/data/projects/project-by-fly-extension-id-mutation.ts +++ b/apps/studio/data/projects/project-by-fly-extension-id-mutation.ts @@ -31,20 +31,18 @@ export const useProjectByFlyExtensionIdMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => getProjectByFlyExtensionId(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to get project: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => getProjectByFlyExtensionId(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to get project: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/projects/project-create-mutation.ts b/apps/studio/data/projects/project-create-mutation.ts index 38a282dd1e6d2..ece39173d9eb2 100644 --- a/apps/studio/data/projects/project-create-mutation.ts +++ b/apps/studio/data/projects/project-create-mutation.ts @@ -95,27 +95,25 @@ export const useProjectCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createProject(vars), - { - async onSuccess(data, variables, context) { - await Promise.all([ - queryClient.invalidateQueries(projectKeys.list()), - queryClient.invalidateQueries(projectKeys.infiniteListByOrg(variables.organizationSlug)), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create new project: ${data.message}`) - } else { - onError(data, variables, context) - } - if (!WHITELIST_ERRORS.some((error) => data.message.includes(error))) { - Sentry.captureMessage('[CRITICAL] Failed to create project: ' + data.message) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createProject(vars), + async onSuccess(data, variables, context) { + await Promise.all([ + queryClient.invalidateQueries(projectKeys.list()), + queryClient.invalidateQueries(projectKeys.infiniteListByOrg(variables.organizationSlug)), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create new project: ${data.message}`) + } else { + onError(data, variables, context) + } + if (!WHITELIST_ERRORS.some((error) => data.message.includes(error))) { + Sentry.captureMessage('[CRITICAL] Failed to create project: ' + data.message) + } + }, + ...options, + }) } diff --git a/apps/studio/data/projects/project-detail-query.ts b/apps/studio/data/projects/project-detail-query.ts index ac03ea6b0f70e..af3d4a636086a 100644 --- a/apps/studio/data/projects/project-detail-query.ts +++ b/apps/studio/data/projects/project-detail-query.ts @@ -44,30 +44,24 @@ export const useProjectDetailQuery = ( { ref }: ProjectDetailVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - projectKeys.detail(ref), - ({ signal }) => getProjectDetail({ ref }, signal), - { - enabled: enabled && typeof ref !== 'undefined', - staleTime: 30 * 1000, // 30 seconds - refetchInterval(data) { - const result = data && (data as unknown as ProjectDetailData) - const status = result && result.status - const connectionString = result && result.connectionString - - if ( - status === 'COMING_UP' || - status === 'UNKNOWN' || - !isValidConnString(connectionString) - ) { - return 5 * 1000 // 5 seconds - } - - return false - }, - ...options, - } - ) + useQuery({ + queryKey: projectKeys.detail(ref), + queryFn: ({ signal }) => getProjectDetail({ ref }, signal), + enabled: enabled && typeof ref !== 'undefined', + staleTime: 30 * 1000, + refetchInterval(data) { + const result = data && (data as unknown as ProjectDetailData) + const status = result && result.status + const connectionString = result && result.connectionString + + if (status === 'COMING_UP' || status === 'UNKNOWN' || !isValidConnString(connectionString)) { + return 5 * 1000 // 5 seconds + } + + return false + }, + ...options, + }) export function prefetchProjectDetail(client: QueryClient, { ref }: ProjectDetailVariables) { return client.fetchQuery(projectKeys.detail(ref), ({ signal }) => diff --git a/apps/studio/data/projects/project-pause-mutation.ts b/apps/studio/data/projects/project-pause-mutation.ts index 9cdbc0ed9634d..df177591361f7 100644 --- a/apps/studio/data/projects/project-pause-mutation.ts +++ b/apps/studio/data/projects/project-pause-mutation.ts @@ -26,20 +26,18 @@ export const useProjectPauseMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => pauseProject(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to pause project: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => pauseProject(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to pause project: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/projects/project-pause-status-query.ts b/apps/studio/data/projects/project-pause-status-query.ts index c84c0b790ec5b..64ed510310160 100644 --- a/apps/studio/data/projects/project-pause-status-query.ts +++ b/apps/studio/data/projects/project-pause-status-query.ts @@ -31,11 +31,9 @@ export const useProjectPauseStatusQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - projectKeys.pauseStatus(ref), - ({ signal }) => getProjectPausedStatus({ ref }, signal), - { - enabled: enabled && typeof ref !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: projectKeys.pauseStatus(ref), + queryFn: ({ signal }) => getProjectPausedStatus({ ref }, signal), + enabled: enabled && typeof ref !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/projects/project-restart-mutation.ts b/apps/studio/data/projects/project-restart-mutation.ts index f8cda402e68a7..064d8a6b50bbe 100644 --- a/apps/studio/data/projects/project-restart-mutation.ts +++ b/apps/studio/data/projects/project-restart-mutation.ts @@ -34,20 +34,18 @@ export const useProjectRestartMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => restartProject(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to restart project: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => restartProject(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to restart project: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/projects/project-restart-services-mutation.ts b/apps/studio/data/projects/project-restart-services-mutation.ts index 1adb15c4bc302..f5703f6b2d38d 100644 --- a/apps/studio/data/projects/project-restart-services-mutation.ts +++ b/apps/studio/data/projects/project-restart-services-mutation.ts @@ -55,20 +55,18 @@ export const useProjectRestartServicesMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => restartProjectServices(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to restart project: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => restartProjectServices(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to restart project: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/projects/project-restore-mutation.ts b/apps/studio/data/projects/project-restore-mutation.ts index 4a3a2fef176d5..7037970e2bc54 100644 --- a/apps/studio/data/projects/project-restore-mutation.ts +++ b/apps/studio/data/projects/project-restore-mutation.ts @@ -37,20 +37,18 @@ export const useProjectRestoreMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => restoreProject(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to restore project: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => restoreProject(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to restore project: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/projects/project-service-versions.ts b/apps/studio/data/projects/project-service-versions.ts index 0fc53482b6815..dabd53811dbdb 100644 --- a/apps/studio/data/projects/project-service-versions.ts +++ b/apps/studio/data/projects/project-service-versions.ts @@ -32,11 +32,9 @@ export const useProjectServiceVersionsQuery = = {} ) => - useQuery( - projectKeys.serviceVersions(projectRef), - ({ signal }) => getProjectServiceVersions({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: projectKeys.serviceVersions(projectRef), + queryFn: ({ signal }) => getProjectServiceVersions({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/projects/project-status-query.ts b/apps/studio/data/projects/project-status-query.ts index 30879f884658a..1503aeb5bd128 100644 --- a/apps/studio/data/projects/project-status-query.ts +++ b/apps/studio/data/projects/project-status-query.ts @@ -30,8 +30,9 @@ export const useProjectStatusQuery = ( { projectRef }: ProjectStatusVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - projectKeys.status(projectRef), - ({ signal }) => getProjectStatus({ projectRef }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: projectKeys.status(projectRef), + queryFn: ({ signal }) => getProjectStatus({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/projects/project-transfer-mutation.ts b/apps/studio/data/projects/project-transfer-mutation.ts index 8d9056c26db0a..82fe0a9ead00a 100644 --- a/apps/studio/data/projects/project-transfer-mutation.ts +++ b/apps/studio/data/projects/project-transfer-mutation.ts @@ -41,28 +41,26 @@ export const useProjectTransferMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => transferProject(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, targetOrganizationSlug } = variables - await Promise.all([ - queryClient.invalidateQueries( - projectKeys.projectTransferPreview(projectRef, targetOrganizationSlug) - ), - queryClient.invalidateQueries(projectKeys.detail(projectRef)), - queryClient.invalidateQueries(projectKeys.list()), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to transfer project: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => transferProject(vars), + async onSuccess(data, variables, context) { + const { projectRef, targetOrganizationSlug } = variables + await Promise.all([ + queryClient.invalidateQueries( + projectKeys.projectTransferPreview(projectRef, targetOrganizationSlug) + ), + queryClient.invalidateQueries(projectKeys.detail(projectRef)), + queryClient.invalidateQueries(projectKeys.list()), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to transfer project: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/projects/project-transfer-preview-query.ts b/apps/studio/data/projects/project-transfer-preview-query.ts index 02fc0cbdb081d..75cc11428e72c 100644 --- a/apps/studio/data/projects/project-transfer-preview-query.ts +++ b/apps/studio/data/projects/project-transfer-preview-query.ts @@ -37,32 +37,27 @@ export const useProjectTransferPreviewQuery = = {} ) => - useQuery( - projectKeys.projectTransferPreview(projectRef, targetOrganizationSlug), - ({ signal }) => previewProjectTransfer({ projectRef, targetOrganizationSlug }, signal), - { - enabled: - enabled && - typeof projectRef !== 'undefined' && - typeof targetOrganizationSlug !== 'undefined', - ...options, - - retry: (failureCount, error) => { - // Don't retry on 400s - if ( - typeof error === 'object' && - error !== null && - 'code' in error && - (error as any).code === 400 - ) { - return false - } + useQuery({ + queryKey: projectKeys.projectTransferPreview(projectRef, targetOrganizationSlug), + queryFn: ({ signal }) => previewProjectTransfer({ projectRef, targetOrganizationSlug }, signal), + enabled: + enabled && typeof projectRef !== 'undefined' && typeof targetOrganizationSlug !== 'undefined', + ...options, + retry: (failureCount, error) => { + // Don't retry on 400s + if ( + typeof error === 'object' && + error !== null && + 'code' in error && + (error as any).code === 400 + ) { + return false + } - if (failureCount < 3) { - return true - } + if (failureCount < 3) { + return true + } - return false - }, - } - ) + return false + }, + }) diff --git a/apps/studio/data/projects/project-type-generation-query.ts b/apps/studio/data/projects/project-type-generation-query.ts index 0f0fb9a99f48b..02fe84604e69f 100644 --- a/apps/studio/data/projects/project-type-generation-query.ts +++ b/apps/studio/data/projects/project-type-generation-query.ts @@ -28,8 +28,9 @@ export const useGenerateTypesQuery = ( { ref, included_schemas }: GenerateTypesVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - projectKeys.types(ref), - ({ signal }) => generateTypes({ ref, included_schemas }, signal), - { enabled: enabled && typeof ref !== 'undefined', ...options } - ) + useQuery({ + queryKey: projectKeys.types(ref), + queryFn: ({ signal }) => generateTypes({ ref, included_schemas }, signal), + enabled: enabled && typeof ref !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/projects/project-update-mutation.ts b/apps/studio/data/projects/project-update-mutation.ts index 68eebe38ebf5d..a6f5fb4a72072 100644 --- a/apps/studio/data/projects/project-update-mutation.ts +++ b/apps/studio/data/projects/project-update-mutation.ts @@ -37,25 +37,23 @@ export const useProjectUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateProject(vars), - { - async onSuccess(data, variables, context) { - const { ref } = variables - await Promise.all([ - queryClient.invalidateQueries(projectKeys.list()), - queryClient.invalidateQueries(projectKeys.detail(ref)), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update project: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateProject(vars), + async onSuccess(data, variables, context) { + const { ref } = variables + await Promise.all([ + queryClient.invalidateQueries(projectKeys.list()), + queryClient.invalidateQueries(projectKeys.detail(ref)), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update project: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/projects/project-upgrade-mutation.ts b/apps/studio/data/projects/project-upgrade-mutation.ts index 28c377a66decf..fb775e73c7777 100644 --- a/apps/studio/data/projects/project-upgrade-mutation.ts +++ b/apps/studio/data/projects/project-upgrade-mutation.ts @@ -32,20 +32,18 @@ export const useProjectUpgradeMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => upgradeProject(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to upgrade project: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => upgradeProject(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to upgrade project: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/projects/projects-query.ts b/apps/studio/data/projects/projects-query.ts index 8c1c11f911116..458d12374b0e5 100644 --- a/apps/studio/data/projects/projects-query.ts +++ b/apps/studio/data/projects/projects-query.ts @@ -34,13 +34,11 @@ export const useProjectsQuery = ({ ...options }: UseQueryOptions = {}) => { const { profile } = useProfile() - return useQuery( - projectKeys.list(), - ({ signal }) => getProjects({ signal }), - { - enabled: enabled && profile !== undefined, - staleTime: 30 * 60 * 1000, // 30 minutes - ...options, - } - ) + return useQuery({ + queryKey: projectKeys.list(), + queryFn: ({ signal }) => getProjects({ signal }), + enabled: enabled && profile !== undefined, + staleTime: 30 * 60 * 1000, + ...options, + }) } diff --git a/apps/studio/data/read-replicas/load-balancers-query.ts b/apps/studio/data/read-replicas/load-balancers-query.ts index 37d35418886a0..1401742cba599 100644 --- a/apps/studio/data/read-replicas/load-balancers-query.ts +++ b/apps/studio/data/read-replicas/load-balancers-query.ts @@ -34,12 +34,10 @@ export const useLoadBalancersQuery = ( { projectRef }: LoadBalancersVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => { - return useQuery( - replicaKeys.loadBalancers(projectRef), - ({ signal }) => getLoadBalancers({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && IS_PLATFORM, - ...options, - } - ) + return useQuery({ + queryKey: replicaKeys.loadBalancers(projectRef), + queryFn: ({ signal }) => getLoadBalancers({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && IS_PLATFORM, + ...options, + }) } diff --git a/apps/studio/data/read-replicas/replica-lag-query.ts b/apps/studio/data/read-replicas/replica-lag-query.ts index 74923d2e6d166..2c224f0ec873f 100644 --- a/apps/studio/data/read-replicas/replica-lag-query.ts +++ b/apps/studio/data/read-replicas/replica-lag-query.ts @@ -45,11 +45,9 @@ export const useReplicationLagQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - replicaKeys.replicaLag(projectRef, id), - ({ signal }) => getReplicationLag({ projectRef, connectionString, id }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: replicaKeys.replicaLag(projectRef, id), + queryFn: ({ signal }) => getReplicationLag({ projectRef, connectionString, id }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/read-replicas/replica-remove-mutation.ts b/apps/studio/data/read-replicas/replica-remove-mutation.ts index 75605f44f5297..dbd3a96136749 100644 --- a/apps/studio/data/read-replicas/replica-remove-mutation.ts +++ b/apps/studio/data/read-replicas/replica-remove-mutation.ts @@ -35,29 +35,27 @@ export const useReadReplicaRemoveMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => removeReadReplica(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, invalidateReplicaQueries } = variables + return useMutation({ + mutationFn: (vars) => removeReadReplica(vars), + async onSuccess(data, variables, context) { + const { projectRef, invalidateReplicaQueries } = variables - if (invalidateReplicaQueries) { - await Promise.all([ - queryClient.invalidateQueries(replicaKeys.list(projectRef)), - queryClient.invalidateQueries(replicaKeys.loadBalancers(projectRef)), - ]) - } + if (invalidateReplicaQueries) { + await Promise.all([ + queryClient.invalidateQueries(replicaKeys.list(projectRef)), + queryClient.invalidateQueries(replicaKeys.loadBalancers(projectRef)), + ]) + } - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to remove read replica: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to remove read replica: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/read-replicas/replica-setup-mutation.ts b/apps/studio/data/read-replicas/replica-setup-mutation.ts index 64b2adfdbdc9b..51a330a9ea1ba 100644 --- a/apps/studio/data/read-replicas/replica-setup-mutation.ts +++ b/apps/studio/data/read-replicas/replica-setup-mutation.ts @@ -51,22 +51,20 @@ export const useReadReplicaSetUpMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => setUpReadReplica(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(replicaKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to set up read replica: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => setUpReadReplica(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(replicaKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to set up read replica: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/read-replicas/replicas-query.ts b/apps/studio/data/read-replicas/replicas-query.ts index 30b885d9d38cd..80d64517f51b9 100644 --- a/apps/studio/data/read-replicas/replicas-query.ts +++ b/apps/studio/data/read-replicas/replicas-query.ts @@ -33,14 +33,12 @@ export const useReadReplicasQuery = ( { projectRef }: ReadReplicasVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => { - return useQuery( - replicaKeys.list(projectRef), - ({ signal }) => getReadReplicas({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + return useQuery({ + queryKey: replicaKeys.list(projectRef), + queryFn: ({ signal }) => getReadReplicas({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) } export const usePrimaryDatabase = ({ projectRef }: { projectRef?: string }) => { diff --git a/apps/studio/data/read-replicas/replicas-status-query.ts b/apps/studio/data/read-replicas/replicas-status-query.ts index b4fc3d061758f..f601b15d0e2ee 100644 --- a/apps/studio/data/read-replicas/replicas-status-query.ts +++ b/apps/studio/data/read-replicas/replicas-status-query.ts @@ -48,12 +48,10 @@ export const useReadReplicasStatusesQuery = ( ...options }: UseQueryOptions = {} ) => { - return useQuery( - replicaKeys.statuses(projectRef), - ({ signal }) => getReadReplicasStatuses({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + return useQuery({ + queryKey: replicaKeys.statuses(projectRef), + queryFn: ({ signal }) => getReadReplicasStatuses({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) } diff --git a/apps/studio/data/realtime/realtime-config-mutation.ts b/apps/studio/data/realtime/realtime-config-mutation.ts index 9629e76c794a3..d2c5d9d1c3f9a 100644 --- a/apps/studio/data/realtime/realtime-config-mutation.ts +++ b/apps/studio/data/realtime/realtime-config-mutation.ts @@ -65,7 +65,8 @@ export const useRealtimeConfigurationUpdateMutation = ({ RealtimeConfigurationUpdateData, ResponseError, RealtimeConfigurationUpdateVariables - >((vars) => updateRealtimeConfiguration(vars), { + >({ + mutationFn: (vars) => updateRealtimeConfiguration(vars), async onSuccess(data, variables, context) { const { ref } = variables await queryClient.invalidateQueries(realtimeKeys.configuration(ref)) diff --git a/apps/studio/data/realtime/realtime-config-query.ts b/apps/studio/data/realtime/realtime-config-query.ts index f9677d13d4865..d5cff6a73f804 100644 --- a/apps/studio/data/realtime/realtime-config-query.ts +++ b/apps/studio/data/realtime/realtime-config-query.ts @@ -52,11 +52,9 @@ export const useRealtimeConfigurationQuery = ...options }: UseQueryOptions = {} ) => - useQuery( - realtimeKeys.configuration(projectRef), - ({ signal }) => getRealtimeConfiguration({ projectRef }, signal), - { - enabled: enabled && IS_PLATFORM && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: realtimeKeys.configuration(projectRef), + queryFn: ({ signal }) => getRealtimeConfiguration({ projectRef }, signal), + enabled: enabled && IS_PLATFORM && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/replication/create-destination-pipeline-mutation.ts b/apps/studio/data/replication/create-destination-pipeline-mutation.ts index 456dc6788462a..9411ae09e9d76 100644 --- a/apps/studio/data/replication/create-destination-pipeline-mutation.ts +++ b/apps/studio/data/replication/create-destination-pipeline-mutation.ts @@ -127,8 +127,8 @@ export const useCreateDestinationPipelineMutation = ({ const queryClient = useQueryClient() return useMutation( - (vars) => createDestinationPipeline(vars), { + mutationFn: (vars) => createDestinationPipeline(vars), async onSuccess(data, variables, context) { const { projectRef } = variables diff --git a/apps/studio/data/replication/create-publication-mutation.ts b/apps/studio/data/replication/create-publication-mutation.ts index 8b721eb686237..ebe3669e7fba4 100644 --- a/apps/studio/data/replication/create-publication-mutation.ts +++ b/apps/studio/data/replication/create-publication-mutation.ts @@ -45,22 +45,20 @@ export const useCreatePublicationMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createPublication(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, sourceId } = variables - await queryClient.invalidateQueries(replicationKeys.publications(projectRef, sourceId)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create publication: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createPublication(vars), + async onSuccess(data, variables, context) { + const { projectRef, sourceId } = variables + await queryClient.invalidateQueries(replicationKeys.publications(projectRef, sourceId)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create publication: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/replication/create-tenant-source-mutation.ts b/apps/studio/data/replication/create-tenant-source-mutation.ts index 12cfe91ec0a62..09c9e02bf1de5 100644 --- a/apps/studio/data/replication/create-tenant-source-mutation.ts +++ b/apps/studio/data/replication/create-tenant-source-mutation.ts @@ -35,22 +35,20 @@ export const useCreateTenantSourceMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createTenantSource(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(replicationKeys.sources(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create tenant or source: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createTenantSource(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(replicationKeys.sources(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create tenant or source: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/replication/delete-destination-pipeline-mutation.ts b/apps/studio/data/replication/delete-destination-pipeline-mutation.ts index 91766e5a80db1..422c78a50332c 100644 --- a/apps/studio/data/replication/delete-destination-pipeline-mutation.ts +++ b/apps/studio/data/replication/delete-destination-pipeline-mutation.ts @@ -44,8 +44,8 @@ export const useDeleteDestinationPipelineMutation = ({ const queryClient = useQueryClient() return useMutation( - (vars) => deleteDestinationPipeline(vars), { + mutationFn: (vars) => deleteDestinationPipeline(vars), async onSuccess(data, variables, context) { const { projectRef, destinationId, pipelineId } = variables diff --git a/apps/studio/data/replication/destination-by-id-query.ts b/apps/studio/data/replication/destination-by-id-query.ts index c595a3e1fd2da..256f7d2497ed3 100644 --- a/apps/studio/data/replication/destination-by-id-query.ts +++ b/apps/studio/data/replication/destination-by-id-query.ts @@ -33,11 +33,9 @@ export const useReplicationDestinationByIdQuery = = {} ) => - useQuery( - replicationKeys.destinationById(projectRef, destinationId), - ({ signal }) => fetchReplicationDestinationById({ projectRef, destinationId }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof destinationId !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: replicationKeys.destinationById(projectRef, destinationId), + queryFn: ({ signal }) => fetchReplicationDestinationById({ projectRef, destinationId }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && typeof destinationId !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/replication/destinations-query.ts b/apps/studio/data/replication/destinations-query.ts index 85449c6be923d..38eb3ac2d2748 100644 --- a/apps/studio/data/replication/destinations-query.ts +++ b/apps/studio/data/replication/destinations-query.ts @@ -32,8 +32,9 @@ export const useReplicationDestinationsQuery = = {} ) => - useQuery( - replicationKeys.destinations(projectRef), - ({ signal }) => fetchReplicationDestinations({ projectRef }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: replicationKeys.destinations(projectRef), + queryFn: ({ signal }) => fetchReplicationDestinations({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/replication/pipeline-by-id-query.ts b/apps/studio/data/replication/pipeline-by-id-query.ts index 91d710ef4f74d..88d537a9b6b0d 100644 --- a/apps/studio/data/replication/pipeline-by-id-query.ts +++ b/apps/studio/data/replication/pipeline-by-id-query.ts @@ -33,11 +33,9 @@ export const useReplicationPipelineByIdQuery = = {} ) => - useQuery( - replicationKeys.pipelineById(projectRef, pipelineId), - ({ signal }) => fetchReplicationPipelineById({ projectRef, pipelineId }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof pipelineId !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: replicationKeys.pipelineById(projectRef, pipelineId), + queryFn: ({ signal }) => fetchReplicationPipelineById({ projectRef, pipelineId }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && typeof pipelineId !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/replication/pipeline-replication-status-query.ts b/apps/studio/data/replication/pipeline-replication-status-query.ts index 952fa97fa4412..faf0769a534fe 100644 --- a/apps/studio/data/replication/pipeline-replication-status-query.ts +++ b/apps/studio/data/replication/pipeline-replication-status-query.ts @@ -40,11 +40,10 @@ export const useReplicationPipelineReplicationStatusQuery = < ...options }: UseQueryOptions = {} ) => - useQuery( - replicationKeys.pipelinesReplicationStatus(projectRef, pipelineId), - ({ signal }) => fetchReplicationPipelineReplicationStatus({ projectRef, pipelineId }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof pipelineId !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: replicationKeys.pipelinesReplicationStatus(projectRef, pipelineId), + queryFn: ({ signal }) => + fetchReplicationPipelineReplicationStatus({ projectRef, pipelineId }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && typeof pipelineId !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/replication/pipeline-status-query.ts b/apps/studio/data/replication/pipeline-status-query.ts index 66aaa6633e2af..0731af7e1af3e 100644 --- a/apps/studio/data/replication/pipeline-status-query.ts +++ b/apps/studio/data/replication/pipeline-status-query.ts @@ -35,11 +35,9 @@ export const useReplicationPipelineStatusQuery = = {} ) => - useQuery( - replicationKeys.pipelinesStatus(projectRef, pipelineId), - ({ signal }) => fetchReplicationPipelineStatus({ projectRef, pipelineId }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof pipelineId !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: replicationKeys.pipelinesStatus(projectRef, pipelineId), + queryFn: ({ signal }) => fetchReplicationPipelineStatus({ projectRef, pipelineId }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && typeof pipelineId !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/replication/pipeline-version-query.ts b/apps/studio/data/replication/pipeline-version-query.ts index ad2e5a7541ec4..9ed514ff57046 100644 --- a/apps/studio/data/replication/pipeline-version-query.ts +++ b/apps/studio/data/replication/pipeline-version-query.ts @@ -37,14 +37,12 @@ export const useReplicationPipelineVersionQuery = = {} ) => - useQuery( - replicationKeys.pipelinesVersion(projectRef, pipelineId), - ({ signal }) => fetchReplicationPipelineVersion({ projectRef, pipelineId }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof pipelineId !== 'undefined', - staleTime, - refetchOnMount, - refetchOnWindowFocus, - ...options, - } - ) + useQuery({ + queryKey: replicationKeys.pipelinesVersion(projectRef, pipelineId), + queryFn: ({ signal }) => fetchReplicationPipelineVersion({ projectRef, pipelineId }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && typeof pipelineId !== 'undefined', + staleTime, + refetchOnMount, + refetchOnWindowFocus, + ...options, + }) diff --git a/apps/studio/data/replication/pipelines-query.ts b/apps/studio/data/replication/pipelines-query.ts index 82d0117f080f0..c21af4e7b2f43 100644 --- a/apps/studio/data/replication/pipelines-query.ts +++ b/apps/studio/data/replication/pipelines-query.ts @@ -33,8 +33,9 @@ export const useReplicationPipelinesQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - replicationKeys.pipelines(projectRef), - ({ signal }) => fetchReplicationPipelines({ projectRef }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: replicationKeys.pipelines(projectRef), + queryFn: ({ signal }) => fetchReplicationPipelines({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/replication/publications-query.ts b/apps/studio/data/replication/publications-query.ts index da56da7d82426..576424cd09aee 100644 --- a/apps/studio/data/replication/publications-query.ts +++ b/apps/studio/data/replication/publications-query.ts @@ -37,11 +37,9 @@ export const useReplicationPublicationsQuery = = {} ) => - useQuery( - replicationKeys.publications(projectRef, sourceId), - ({ signal }) => fetchReplicationPublications({ projectRef, sourceId }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof sourceId !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: replicationKeys.publications(projectRef, sourceId), + queryFn: ({ signal }) => fetchReplicationPublications({ projectRef, sourceId }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && typeof sourceId !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/replication/rollback-table-mutation.ts b/apps/studio/data/replication/rollback-table-mutation.ts index 0dbd02185e843..5c5b8776c2d1b 100644 --- a/apps/studio/data/replication/rollback-table-mutation.ts +++ b/apps/studio/data/replication/rollback-table-mutation.ts @@ -57,28 +57,26 @@ export const useRollbackTableMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => rollbackTableState(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, pipelineId } = variables - await Promise.all([ - queryClient.invalidateQueries(replicationKeys.pipelinesStatus(projectRef, pipelineId)), - queryClient.invalidateQueries( - replicationKeys.pipelinesReplicationStatus(projectRef, pipelineId) - ), - ]) + return useMutation({ + mutationFn: (vars) => rollbackTableState(vars), + async onSuccess(data, variables, context) { + const { projectRef, pipelineId } = variables + await Promise.all([ + queryClient.invalidateQueries(replicationKeys.pipelinesStatus(projectRef, pipelineId)), + queryClient.invalidateQueries( + replicationKeys.pipelinesReplicationStatus(projectRef, pipelineId) + ), + ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to rollback table: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to rollback table: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/replication/sources-query.ts b/apps/studio/data/replication/sources-query.ts index 3009b432fa7a0..3fd68761f8713 100644 --- a/apps/studio/data/replication/sources-query.ts +++ b/apps/studio/data/replication/sources-query.ts @@ -29,8 +29,9 @@ export const useReplicationSourcesQuery = ( { projectRef }: ReplicationSourcesParams, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - replicationKeys.sources(projectRef), - ({ signal }) => fetchReplicationSources({ projectRef }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: replicationKeys.sources(projectRef), + queryFn: ({ signal }) => fetchReplicationSources({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/replication/start-pipeline-mutation.ts b/apps/studio/data/replication/start-pipeline-mutation.ts index 7bcf93917c989..df6926492341f 100644 --- a/apps/studio/data/replication/start-pipeline-mutation.ts +++ b/apps/studio/data/replication/start-pipeline-mutation.ts @@ -39,22 +39,20 @@ export const useStartPipelineMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => startPipeline(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, pipelineId } = variables - await queryClient.invalidateQueries(replicationKeys.pipelinesStatus(projectRef, pipelineId)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to start pipeline: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => startPipeline(vars), + async onSuccess(data, variables, context) { + const { projectRef, pipelineId } = variables + await queryClient.invalidateQueries(replicationKeys.pipelinesStatus(projectRef, pipelineId)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to start pipeline: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/replication/stop-pipeline-mutation.ts b/apps/studio/data/replication/stop-pipeline-mutation.ts index ab4c63bcbecc1..e662f81ac810d 100644 --- a/apps/studio/data/replication/stop-pipeline-mutation.ts +++ b/apps/studio/data/replication/stop-pipeline-mutation.ts @@ -36,22 +36,20 @@ export const useStopPipelineMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => stopPipeline(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, pipelineId } = variables - await queryClient.invalidateQueries(replicationKeys.pipelinesStatus(projectRef, pipelineId)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to stop pipeline: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => stopPipeline(vars), + async onSuccess(data, variables, context) { + const { projectRef, pipelineId } = variables + await queryClient.invalidateQueries(replicationKeys.pipelinesStatus(projectRef, pipelineId)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to stop pipeline: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/replication/tables-query.ts b/apps/studio/data/replication/tables-query.ts index 42a7256f1d9de..7da559b113935 100644 --- a/apps/studio/data/replication/tables-query.ts +++ b/apps/studio/data/replication/tables-query.ts @@ -30,11 +30,9 @@ export const useReplicationTablesQuery = ( { projectRef, sourceId }: ReplicationTablesParams, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - replicationKeys.tables(projectRef, sourceId), - ({ signal }) => fetchReplicationTables({ projectRef, sourceId }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof sourceId !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: replicationKeys.tables(projectRef, sourceId), + queryFn: ({ signal }) => fetchReplicationTables({ projectRef, sourceId }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && typeof sourceId !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/replication/update-destination-pipeline-mutation.ts b/apps/studio/data/replication/update-destination-pipeline-mutation.ts index 04d37d9f6702e..0c852bd54286d 100644 --- a/apps/studio/data/replication/update-destination-pipeline-mutation.ts +++ b/apps/studio/data/replication/update-destination-pipeline-mutation.ts @@ -131,8 +131,8 @@ export const useUpdateDestinationPipelineMutation = ({ const queryClient = useQueryClient() return useMutation( - (vars) => updateDestinationPipeline(vars), { + mutationFn: (vars) => updateDestinationPipeline(vars), async onSuccess(data, variables, context) { const { projectRef, destinationId, pipelineId } = variables diff --git a/apps/studio/data/replication/update-pipeline-version-mutation.ts b/apps/studio/data/replication/update-pipeline-version-mutation.ts index 0ee9bc43a3ebd..6c1fa664104c1 100644 --- a/apps/studio/data/replication/update-pipeline-version-mutation.ts +++ b/apps/studio/data/replication/update-pipeline-version-mutation.ts @@ -44,31 +44,27 @@ export const useUpdatePipelineVersionMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updatePipelineVersion(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, pipelineId } = variables - // Ensure the version dot updates promptly + return useMutation({ + mutationFn: (vars) => updatePipelineVersion(vars), + async onSuccess(data, variables, context) { + const { projectRef, pipelineId } = variables + // Ensure the version dot updates promptly + await queryClient.invalidateQueries(replicationKeys.pipelinesVersion(projectRef, pipelineId)) + await onSuccess?.(data, variables, context) + }, + async onError(error, variables, context) { + const { projectRef, pipelineId } = variables + if (error?.code === 404) { + // Default image changed meanwhile. Refresh version info so UI reflects latest state. await queryClient.invalidateQueries( replicationKeys.pipelinesVersion(projectRef, pipelineId) ) - await onSuccess?.(data, variables, context) - }, - async onError(error, variables, context) { - const { projectRef, pipelineId } = variables - if (error?.code === 404) { - // Default image changed meanwhile. Refresh version info so UI reflects latest state. - await queryClient.invalidateQueries( - replicationKeys.pipelinesVersion(projectRef, pipelineId) - ) - } else if (onError === undefined) { - toast.error(`Failed to update pipeline version: ${error.message}`) - } else { - onError(error, variables, context) - } - }, - ...options, - } - ) + } else if (onError === undefined) { + toast.error(`Failed to update pipeline version: ${error.message}`) + } else { + onError(error, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/secrets/secrets-create-mutation.ts b/apps/studio/data/secrets/secrets-create-mutation.ts index dc02c8a212bf3..52d6c7cb23430 100644 --- a/apps/studio/data/secrets/secrets-create-mutation.ts +++ b/apps/studio/data/secrets/secrets-create-mutation.ts @@ -33,22 +33,20 @@ export const useSecretsCreateMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createSecrets(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(secretsKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create secrets: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createSecrets(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(secretsKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create secrets: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/secrets/secrets-delete-mutation.ts b/apps/studio/data/secrets/secrets-delete-mutation.ts index 9ce21fbd6b151..1a40214fb2db2 100644 --- a/apps/studio/data/secrets/secrets-delete-mutation.ts +++ b/apps/studio/data/secrets/secrets-delete-mutation.ts @@ -33,22 +33,20 @@ export const useSecretsDeleteMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteSecrets(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(secretsKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete secrets: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteSecrets(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(secretsKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete secrets: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/secrets/secrets-query.ts b/apps/studio/data/secrets/secrets-query.ts index 0219cda3705ff..ae41c2455b398 100644 --- a/apps/studio/data/secrets/secrets-query.ts +++ b/apps/studio/data/secrets/secrets-query.ts @@ -30,8 +30,9 @@ export const useSecretsQuery = ( { projectRef }: SecretsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - secretsKeys.list(projectRef), - ({ signal }) => getSecrets({ projectRef }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: secretsKeys.list(projectRef), + queryFn: ({ signal }) => getSecrets({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/service-status/edge-functions-status-query.ts b/apps/studio/data/service-status/edge-functions-status-query.ts index ea97a0b41411a..f21c992cb939f 100644 --- a/apps/studio/data/service-status/edge-functions-status-query.ts +++ b/apps/studio/data/service-status/edge-functions-status-query.ts @@ -30,11 +30,9 @@ export const useEdgeFunctionServiceStatusQuery = = {} ) => - useQuery( - serviceStatusKeys.edgeFunctions(projectRef), - ({ signal }) => getEdgeFunctionServiceStatus(signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: serviceStatusKeys.edgeFunctions(projectRef), + queryFn: ({ signal }) => getEdgeFunctionServiceStatus(signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/service-status/service-status-query.ts b/apps/studio/data/service-status/service-status-query.ts index 78eb015b8ff02..2ae7ea7908926 100644 --- a/apps/studio/data/service-status/service-status-query.ts +++ b/apps/studio/data/service-status/service-status-query.ts @@ -39,11 +39,9 @@ export const useProjectServiceStatusQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - serviceStatusKeys.serviceStatus(projectRef), - ({ signal }) => getProjectServiceStatus({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: serviceStatusKeys.serviceStatus(projectRef), + queryFn: ({ signal }) => getProjectServiceStatus({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/sql/abort-query-mutation.ts b/apps/studio/data/sql/abort-query-mutation.ts index 2462c8ce76ebe..4cf9ee09ce170 100644 --- a/apps/studio/data/sql/abort-query-mutation.ts +++ b/apps/studio/data/sql/abort-query-mutation.ts @@ -28,22 +28,20 @@ export const useQueryAbortMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => abortQuery(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(sqlKeys.ongoingQueries(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to abort query: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => abortQuery(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(sqlKeys.ongoingQueries(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to abort query: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/sql/execute-sql-mutation.ts b/apps/studio/data/sql/execute-sql-mutation.ts index 91af532e4a4be..5a286142f6abf 100644 --- a/apps/studio/data/sql/execute-sql-mutation.ts +++ b/apps/studio/data/sql/execute-sql-mutation.ts @@ -37,57 +37,55 @@ export const useExecuteSqlMutation = ({ const { mutate: sendEvent } = useSendEventMutation() const { data: org } = useSelectedOrganizationQuery() - return useMutation( - (args) => executeSql(args), - { - async onSuccess(data, variables, context) { - const { contextualInvalidation, sql, projectRef } = variables + return useMutation({ + mutationFn: (args) => executeSql(args), + async onSuccess(data, variables, context) { + const { contextualInvalidation, sql, projectRef } = variables - // Track all table-related events from SQL execution - try { - const tableEvents = sqlEventParser.getTableEvents(sql) - tableEvents.forEach((event) => { - if (projectRef) { - sendEvent({ - action: event.type, - properties: { - method: 'sql_editor', - schema_name: event.schema, - table_name: event.tableName, - }, - groups: { - project: projectRef, - ...(org?.slug && { organization: org.slug }), - }, - }) - } - }) - } catch (error) { - console.error('Failed to parse SQL for telemetry:', error) - } + // Track all table-related events from SQL execution + try { + const tableEvents = sqlEventParser.getTableEvents(sql) + tableEvents.forEach((event) => { + if (projectRef) { + sendEvent({ + action: event.type, + properties: { + method: 'sql_editor', + schema_name: event.schema, + table_name: event.tableName, + }, + groups: { + project: projectRef, + ...(org?.slug && { organization: org.slug }), + }, + }) + } + }) + } catch (error) { + console.error('Failed to parse SQL for telemetry:', error) + } - // [Joshen] Default to false for now, only used for SQL editor to dynamically invalidate - const sqlLower = sql.toLowerCase() - const isMutationSQL = - sqlLower.includes('create ') || sqlLower.includes('alter ') || sqlLower.includes('drop ') - if (contextualInvalidation && projectRef && isMutationSQL) { - const databaseRelatedKeys = queryClient - .getQueryCache() - .findAll(['projects', projectRef]) - .map((x) => x.queryKey) - .filter((x) => !INVALIDATION_KEYS_IGNORE.some((a) => x.includes(a))) - await Promise.all(databaseRelatedKeys.map((key) => queryClient.invalidateQueries(key))) - } - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to execute SQL: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + // [Joshen] Default to false for now, only used for SQL editor to dynamically invalidate + const sqlLower = sql.toLowerCase() + const isMutationSQL = + sqlLower.includes('create ') || sqlLower.includes('alter ') || sqlLower.includes('drop ') + if (contextualInvalidation && projectRef && isMutationSQL) { + const databaseRelatedKeys = queryClient + .getQueryCache() + .findAll(['projects', projectRef]) + .map((x) => x.queryKey) + .filter((x) => !INVALIDATION_KEYS_IGNORE.some((a) => x.includes(a))) + await Promise.all(databaseRelatedKeys.map((key) => queryClient.invalidateQueries(key))) + } + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to execute SQL: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/sql/execute-sql-query.ts b/apps/studio/data/sql/execute-sql-query.ts index b05173c010273..94d7dee705650 100644 --- a/apps/studio/data/sql/execute-sql-query.ts +++ b/apps/studio/data/sql/execute-sql-query.ts @@ -162,13 +162,15 @@ export const useExecuteSqlQuery = ( const { data: project } = useSelectedProjectQuery() const isActive = project?.status === PROJECT_STATUS.ACTIVE_HEALTHY - return useQuery( - sqlKeys.query(projectRef, queryKey ?? [btoa(sql)]), - ({ signal }) => + return useQuery({ + queryKey: sqlKeys.query(projectRef, queryKey ?? [btoa(sql)]), + queryFn: ({ signal }) => executeSql( { projectRef, connectionString, sql, queryKey, handleError, isRoleImpersonationEnabled }, signal ), - { enabled: enabled && typeof projectRef !== 'undefined' && isActive, staleTime: 0, ...options } - ) + enabled: enabled && typeof projectRef !== 'undefined' && isActive, + staleTime: 0, + ...options, + }) } diff --git a/apps/studio/data/sql/ongoing-queries-query.ts b/apps/studio/data/sql/ongoing-queries-query.ts index 5f88f39f0537b..6d981fc27a23b 100644 --- a/apps/studio/data/sql/ongoing-queries-query.ts +++ b/apps/studio/data/sql/ongoing-queries-query.ts @@ -45,11 +45,9 @@ export const useOngoingQueriesQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - sqlKeys.ongoingQueries(projectRef), - ({ signal }) => getOngoingQueries({ projectRef, connectionString }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: sqlKeys.ongoingQueries(projectRef), + queryFn: ({ signal }) => getOngoingQueries({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/ssl-enforcement/ssl-enforcement-query.ts b/apps/studio/data/ssl-enforcement/ssl-enforcement-query.ts index 142074740e316..c9888ee01639e 100644 --- a/apps/studio/data/ssl-enforcement/ssl-enforcement-query.ts +++ b/apps/studio/data/ssl-enforcement/ssl-enforcement-query.ts @@ -46,8 +46,9 @@ export const useSSLEnforcementQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - sslEnforcementKeys.list(projectRef), - ({ signal }) => getSSLEnforcementConfiguration({ projectRef }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: sslEnforcementKeys.list(projectRef), + queryFn: ({ signal }) => getSSLEnforcementConfiguration({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/ssl-enforcement/ssl-enforcement-update-mutation.ts b/apps/studio/data/ssl-enforcement/ssl-enforcement-update-mutation.ts index 626c700981459..dee05de43fa29 100644 --- a/apps/studio/data/ssl-enforcement/ssl-enforcement-update-mutation.ts +++ b/apps/studio/data/ssl-enforcement/ssl-enforcement-update-mutation.ts @@ -43,22 +43,20 @@ export const useSSLEnforcementUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateSSLEnforcement(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(sslEnforcementKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update SSL enforcement: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateSSLEnforcement(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(sslEnforcementKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update SSL enforcement: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/sso/sso-config-create-mutation.ts b/apps/studio/data/sso/sso-config-create-mutation.ts index b8df359367f52..8ad0e79e129ac 100644 --- a/apps/studio/data/sso/sso-config-create-mutation.ts +++ b/apps/studio/data/sso/sso-config-create-mutation.ts @@ -33,22 +33,20 @@ export const useSSOConfigCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createSSOConfig(vars), - { - async onSuccess(data, variables, context) { - const { slug } = variables - await queryClient.invalidateQueries(orgSSOKeys.orgSSOConfig(slug)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create SSO configuration: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createSSOConfig(vars), + async onSuccess(data, variables, context) { + const { slug } = variables + await queryClient.invalidateQueries(orgSSOKeys.orgSSOConfig(slug)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create SSO configuration: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/sso/sso-config-query.ts b/apps/studio/data/sso/sso-config-query.ts index 5651b7da8a37c..33a4d0ab89845 100644 --- a/apps/studio/data/sso/sso-config-query.ts +++ b/apps/studio/data/sso/sso-config-query.ts @@ -43,12 +43,10 @@ export const useOrgSSOConfigQuery = ( const plan = organization?.plan.id const canSetupSSOConfig = ['team', 'enterprise'].includes(plan ?? '') - return useQuery( - orgSSOKeys.orgSSOConfig(orgSlug), - ({ signal }) => getOrgSSOConfig({ orgSlug }, signal), - { - enabled: enabled && IS_PLATFORM && typeof orgSlug !== 'undefined' && canSetupSSOConfig, - ...options, - } - ) + return useQuery({ + queryKey: orgSSOKeys.orgSSOConfig(orgSlug), + queryFn: ({ signal }) => getOrgSSOConfig({ orgSlug }, signal), + enabled: enabled && IS_PLATFORM && typeof orgSlug !== 'undefined' && canSetupSSOConfig, + ...options, + }) } diff --git a/apps/studio/data/sso/sso-config-update-mutation.ts b/apps/studio/data/sso/sso-config-update-mutation.ts index cca2b2fa7e91e..6391dd1398351 100644 --- a/apps/studio/data/sso/sso-config-update-mutation.ts +++ b/apps/studio/data/sso/sso-config-update-mutation.ts @@ -33,26 +33,24 @@ export const useSSOConfigUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateSSOConfig(vars), - { - async onSuccess(data, variables, context) { - const { slug } = variables - await queryClient.invalidateQueries(orgSSOKeys.orgSSOConfig(slug)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - if (data.message === '') { - toast.error(`Failed to update SSO configuration.`) - } else { - toast.error(`${data.message}`) - } + return useMutation({ + mutationFn: (vars) => updateSSOConfig(vars), + async onSuccess(data, variables, context) { + const { slug } = variables + await queryClient.invalidateQueries(orgSSOKeys.orgSSOConfig(slug)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + if (data.message === '') { + toast.error(`Failed to update SSO configuration.`) } else { - onError(data, variables, context) + toast.error(`${data.message}`) } - }, - ...options, - } - ) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/storage/bucket-create-mutation.ts b/apps/studio/data/storage/bucket-create-mutation.ts index b276e75ba1196..87becc9ec91f5 100644 --- a/apps/studio/data/storage/bucket-create-mutation.ts +++ b/apps/studio/data/storage/bucket-create-mutation.ts @@ -51,22 +51,20 @@ export const useBucketCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createBucket(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - 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, - } - ) + return useMutation({ + mutationFn: (vars) => createBucket(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + 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/apps/studio/data/storage/bucket-delete-mutation.ts b/apps/studio/data/storage/bucket-delete-mutation.ts index 383a4331eb797..736b3d1a77d32 100644 --- a/apps/studio/data/storage/bucket-delete-mutation.ts +++ b/apps/studio/data/storage/bucket-delete-mutation.ts @@ -42,22 +42,20 @@ export const useBucketDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteBucket(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - 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, - } - ) + return useMutation({ + mutationFn: (vars) => deleteBucket(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + 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/apps/studio/data/storage/bucket-empty-mutation.ts b/apps/studio/data/storage/bucket-empty-mutation.ts index 29d87a9496faa..6e092848b904a 100644 --- a/apps/studio/data/storage/bucket-empty-mutation.ts +++ b/apps/studio/data/storage/bucket-empty-mutation.ts @@ -34,22 +34,20 @@ export const useBucketEmptyMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => emptyBucket(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(storageKeys.buckets(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to empty bucket: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => emptyBucket(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(storageKeys.buckets(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to empty bucket: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/storage/bucket-object-delete-mutation.ts b/apps/studio/data/storage/bucket-object-delete-mutation.ts index 20b80f10f03e8..4e2a474de3b40 100644 --- a/apps/studio/data/storage/bucket-object-delete-mutation.ts +++ b/apps/studio/data/storage/bucket-object-delete-mutation.ts @@ -43,21 +43,19 @@ export const useBucketObjectDeleteMutation = ({ 'mutationFn' > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteBucketObject(vars), - { - async onSuccess(data, variables, context) { - // [Joshen] TODO figure out what queries to invalidate - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete bucket object: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteBucketObject(vars), + async onSuccess(data, variables, context) { + // [Joshen] TODO figure out what queries to invalidate + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete bucket object: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/storage/bucket-object-download-mutation.ts b/apps/studio/data/storage/bucket-object-download-mutation.ts index 02073d937ffa3..ce36130170b57 100644 --- a/apps/studio/data/storage/bucket-object-download-mutation.ts +++ b/apps/studio/data/storage/bucket-object-download-mutation.ts @@ -37,20 +37,18 @@ export const useBucketObjectDownloadMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => downloadBucketObject(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to download bucket object: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => downloadBucketObject(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to download bucket object: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/storage/bucket-object-get-public-url-mutation.ts b/apps/studio/data/storage/bucket-object-get-public-url-mutation.ts index 810b724ee70ad..51987b6630409 100644 --- a/apps/studio/data/storage/bucket-object-get-public-url-mutation.ts +++ b/apps/studio/data/storage/bucket-object-get-public-url-mutation.ts @@ -42,20 +42,18 @@ export const useGetBucketObjectPublicUrlMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (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, - } - ) + return useMutation({ + 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, + }) } diff --git a/apps/studio/data/storage/bucket-object-sign-mutation.ts b/apps/studio/data/storage/bucket-object-sign-mutation.ts index 34600f8a4592c..e6857bfe833b2 100644 --- a/apps/studio/data/storage/bucket-object-sign-mutation.ts +++ b/apps/studio/data/storage/bucket-object-sign-mutation.ts @@ -43,20 +43,18 @@ export const useGetSignBucketObjectMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => signBucketObject(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to get sign bucket object: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => signBucketObject(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to get sign bucket object: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/storage/bucket-objects-list-mutation.ts b/apps/studio/data/storage/bucket-objects-list-mutation.ts index da97ab1718f73..a951d23918c63 100644 --- a/apps/studio/data/storage/bucket-objects-list-mutation.ts +++ b/apps/studio/data/storage/bucket-objects-list-mutation.ts @@ -49,20 +49,18 @@ export const useGetSignBucketObjectMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => listBucketObjects(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to list bucket objects: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => listBucketObjects(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to list bucket objects: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/storage/bucket-update-mutation.ts b/apps/studio/data/storage/bucket-update-mutation.ts index 2ba8f6b8e6b67..489a4666341a3 100644 --- a/apps/studio/data/storage/bucket-update-mutation.ts +++ b/apps/studio/data/storage/bucket-update-mutation.ts @@ -63,28 +63,26 @@ export const useBucketUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - async (vars) => { + return useMutation({ + mutationFn: async (vars) => { const result = await updateBucket(vars) if (result.error) { throw result.error } return result.data }, - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - 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, - } - ) + async onSuccess(data, variables, context) { + const { projectRef } = variables + 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, + }) } diff --git a/apps/studio/data/storage/buckets-query.ts b/apps/studio/data/storage/buckets-query.ts index 814c9d941c4a8..0779e0d9f6369 100644 --- a/apps/studio/data/storage/buckets-query.ts +++ b/apps/studio/data/storage/buckets-query.ts @@ -35,28 +35,26 @@ export const useBucketsQuery = ( const { data: project } = useSelectedProjectQuery() const isActive = project?.status === PROJECT_STATUS.ACTIVE_HEALTHY - return useQuery( - storageKeys.buckets(projectRef), - ({ signal }) => getBuckets({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && isActive, - ...options, - retry: (failureCount, error) => { - if ( - typeof error === 'object' && - error !== null && - error.message.startsWith('Tenant config') && - error.message.endsWith('not found') - ) { - return false - } - - if (failureCount < 3) { - return true - } - + return useQuery({ + queryKey: storageKeys.buckets(projectRef), + queryFn: ({ signal }) => getBuckets({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined' && isActive, + ...options, + retry: (failureCount, error) => { + if ( + typeof error === 'object' && + error !== null && + error.message.startsWith('Tenant config') && + error.message.endsWith('not found') + ) { return false - }, - } - ) + } + + if (failureCount < 3) { + return true + } + + return false + }, + }) } diff --git a/apps/studio/data/storage/iceberg-namespace-create-mutation.ts b/apps/studio/data/storage/iceberg-namespace-create-mutation.ts index 53ecb59444360..19abdadcc41b2 100644 --- a/apps/studio/data/storage/iceberg-namespace-create-mutation.ts +++ b/apps/studio/data/storage/iceberg-namespace-create-mutation.ts @@ -70,34 +70,28 @@ export const useIcebergNamespaceCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createIcebergNamespace(vars), - { - async onSuccess(data, variables, context) { - await queryClient.invalidateQueries( - storageKeys.icebergNamespace( - variables.catalogUri, - variables.warehouse, - variables.namespace - ) - ) - await queryClient.invalidateQueries( - storageKeys.icebergNamespaces(variables.catalogUri, variables.warehouse) - ) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if ((data.message = 'Request failed with status code 409')) { - toast.error(`A namespace named ${variables.namespace} already exists in the catalog.`) - return - } - if (onError === undefined) { - toast.error(`Failed to create Iceberg namespace: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createIcebergNamespace(vars), + async onSuccess(data, variables, context) { + await queryClient.invalidateQueries( + storageKeys.icebergNamespace(variables.catalogUri, variables.warehouse, variables.namespace) + ) + await queryClient.invalidateQueries( + storageKeys.icebergNamespaces(variables.catalogUri, variables.warehouse) + ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if ((data.message = 'Request failed with status code 409')) { + toast.error(`A namespace named ${variables.namespace} already exists in the catalog.`) + return + } + if (onError === undefined) { + toast.error(`Failed to create Iceberg namespace: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/storage/iceberg-namespace-exists-query.ts b/apps/studio/data/storage/iceberg-namespace-exists-query.ts index 7dfcda400ff36..619ec73f6a423 100644 --- a/apps/studio/data/storage/iceberg-namespace-exists-query.ts +++ b/apps/studio/data/storage/iceberg-namespace-exists-query.ts @@ -56,9 +56,9 @@ export const useIcebergNamespaceExistsQuery = = {} ) => { - return useQuery( - storageKeys.icebergNamespace(params.catalogUri, params.warehouse, params.namespace), - () => checkNamespaceExists(params), - { ...options } - ) + return useQuery({ + queryKey: storageKeys.icebergNamespace(params.catalogUri, params.warehouse, params.namespace), + queryFn: () => checkNamespaceExists(params), + ...options, + }) } diff --git a/apps/studio/data/storage/iceberg-namespace-tables-query.ts b/apps/studio/data/storage/iceberg-namespace-tables-query.ts index ff189ec5e5aa9..2e642578060bb 100644 --- a/apps/studio/data/storage/iceberg-namespace-tables-query.ts +++ b/apps/studio/data/storage/iceberg-namespace-tables-query.ts @@ -67,9 +67,13 @@ export const useIcebergNamespaceTablesQuery = = {} ) => { - return useQuery( - storageKeys.icebergNamespaceTables(params.catalogUri, params.warehouse, params.namespace), - () => getNamespaceTables(params), - { ...options } - ) + return useQuery({ + queryKey: storageKeys.icebergNamespaceTables( + params.catalogUri, + params.warehouse, + params.namespace + ), + queryFn: () => getNamespaceTables(params), + ...options, + }) } diff --git a/apps/studio/data/storage/iceberg-namespaces-query.ts b/apps/studio/data/storage/iceberg-namespaces-query.ts index 6671670a85826..7becfb28c1211 100644 --- a/apps/studio/data/storage/iceberg-namespaces-query.ts +++ b/apps/studio/data/storage/iceberg-namespaces-query.ts @@ -57,9 +57,9 @@ export const useIcebergNamespacesQuery = ( params: GetNamespacesVariables, { ...options }: UseQueryOptions = {} ) => { - return useQuery( - storageKeys.icebergNamespaces(params.catalogUri, params.warehouse), - () => getNamespaces(params), - { ...options } - ) + return useQuery({ + queryKey: storageKeys.icebergNamespaces(params.catalogUri, params.warehouse), + queryFn: () => getNamespaces(params), + ...options, + }) } diff --git a/apps/studio/data/storage/object-move-mutation.ts b/apps/studio/data/storage/object-move-mutation.ts index 91f44e9f0c76d..577589c79adb3 100644 --- a/apps/studio/data/storage/object-move-mutation.ts +++ b/apps/studio/data/storage/object-move-mutation.ts @@ -45,20 +45,18 @@ export const useGetSignBucketObjectMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => moveStorageObject(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to move bucket object: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => moveStorageObject(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to move bucket object: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/storage/s3-access-key-create-mutation.ts b/apps/studio/data/storage/s3-access-key-create-mutation.ts index b1e3a9d37eeab..be716528f5afd 100644 --- a/apps/studio/data/storage/s3-access-key-create-mutation.ts +++ b/apps/studio/data/storage/s3-access-key-create-mutation.ts @@ -37,22 +37,20 @@ export function useS3AccessKeyCreateMutation({ > = {}) { const queryClient = useQueryClient() - return useMutation( - (vars) => createS3AccessKeyCredential(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(storageCredentialsKeys.credentials(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create S3 access key: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createS3AccessKeyCredential(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(storageCredentialsKeys.credentials(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create S3 access key: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/storage/s3-access-key-delete-mutation.ts b/apps/studio/data/storage/s3-access-key-delete-mutation.ts index 06b22c9676b16..0007462375835 100644 --- a/apps/studio/data/storage/s3-access-key-delete-mutation.ts +++ b/apps/studio/data/storage/s3-access-key-delete-mutation.ts @@ -40,22 +40,20 @@ export function useS3AccessKeyDeleteMutation({ > = {}) { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteS3AccessKeyCredential(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(storageCredentialsKeys.credentials(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete S3 access key: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteS3AccessKeyCredential(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(storageCredentialsKeys.credentials(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete S3 access key: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/storage/s3-access-key-query.ts b/apps/studio/data/storage/s3-access-key-query.ts index 9bef91e3b3c37..ffdc0243653d9 100644 --- a/apps/studio/data/storage/s3-access-key-query.ts +++ b/apps/studio/data/storage/s3-access-key-query.ts @@ -37,8 +37,9 @@ export const useStorageCredentialsQuery = ( { projectRef }: StorageCredentialsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - storageCredentialsKeys.credentials(projectRef), - ({ signal }) => fetchStorageCredentials({ projectRef }, signal), - { enabled: enabled && IS_PLATFORM && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: storageCredentialsKeys.credentials(projectRef), + queryFn: ({ signal }) => fetchStorageCredentials({ projectRef }, signal), + enabled: enabled && IS_PLATFORM && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/storage/storage-archive-create-mutation.ts b/apps/studio/data/storage/storage-archive-create-mutation.ts index bf193ab0189bf..90f0dab6fc889 100644 --- a/apps/studio/data/storage/storage-archive-create-mutation.ts +++ b/apps/studio/data/storage/storage-archive-create-mutation.ts @@ -32,22 +32,20 @@ export function useStorageArchiveCreateMutation({ > = {}) { const queryClient = useQueryClient() - return useMutation( - (vars) => createStorageArchive(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(storageKeys.archive(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create storage archive: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createStorageArchive(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(storageKeys.archive(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create storage archive: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/storage/storage-archive-query.ts b/apps/studio/data/storage/storage-archive-query.ts index 3d22152af0c28..cd570a3bc5950 100644 --- a/apps/studio/data/storage/storage-archive-query.ts +++ b/apps/studio/data/storage/storage-archive-query.ts @@ -29,8 +29,9 @@ export const useStorageArchiveQuery = ( { projectRef }: StorageArchiveVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - storageKeys.archive(projectRef), - ({ signal }) => fetchStorageArchive({ projectRef }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + useQuery({ + queryKey: storageKeys.archive(projectRef), + queryFn: ({ signal }) => fetchStorageArchive({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/stripe/setup-intent-mutation.ts b/apps/studio/data/stripe/setup-intent-mutation.ts index fe4bb833e8474..6cae09272f61b 100644 --- a/apps/studio/data/stripe/setup-intent-mutation.ts +++ b/apps/studio/data/stripe/setup-intent-mutation.ts @@ -29,20 +29,18 @@ export const useSetupIntent = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => setupIntent(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to setup intent: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => setupIntent(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to setup intent: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/subscriptions/org-plans-query.ts b/apps/studio/data/subscriptions/org-plans-query.ts index ab1a68ee525f9..502b2c420b33f 100644 --- a/apps/studio/data/subscriptions/org-plans-query.ts +++ b/apps/studio/data/subscriptions/org-plans-query.ts @@ -32,12 +32,10 @@ export const useOrgPlansQuery = ( 'stripe.subscriptions' ) - return useQuery( - subscriptionKeys.orgPlans(orgSlug), - ({ signal }) => getOrgPlans({ orgSlug }, signal), - { - enabled: enabled && typeof orgSlug !== 'undefined' && canReadSubscriptions, - ...options, - } - ) + return useQuery({ + queryKey: subscriptionKeys.orgPlans(orgSlug), + queryFn: ({ signal }) => getOrgPlans({ orgSlug }, signal), + enabled: enabled && typeof orgSlug !== 'undefined' && canReadSubscriptions, + ...options, + }) } diff --git a/apps/studio/data/subscriptions/org-subscription-confirm-pending-change.ts b/apps/studio/data/subscriptions/org-subscription-confirm-pending-change.ts index 7aad279c93cce..ada01d200e472 100644 --- a/apps/studio/data/subscriptions/org-subscription-confirm-pending-change.ts +++ b/apps/studio/data/subscriptions/org-subscription-confirm-pending-change.ts @@ -60,7 +60,8 @@ export const useConfirmPendingSubscriptionChangeMutation = ({ PendingSubscriptionChangeData, ResponseError, PendingSubscriptionChangeVariables - >((vars) => confirmPendingSubscriptionChange(vars), { + >({ + mutationFn: (vars) => confirmPendingSubscriptionChange(vars), async onSuccess(data, variables, context) { const { slug } = variables diff --git a/apps/studio/data/subscriptions/org-subscription-confirm-pending-create.ts b/apps/studio/data/subscriptions/org-subscription-confirm-pending-create.ts index dc41f110121ec..af5c13100d5d1 100644 --- a/apps/studio/data/subscriptions/org-subscription-confirm-pending-create.ts +++ b/apps/studio/data/subscriptions/org-subscription-confirm-pending-create.ts @@ -54,7 +54,8 @@ export const useConfirmPendingSubscriptionCreateMutation = ({ PendingSubscriptionCreateData, ResponseError, PendingSubscriptionCreateVariables - >((vars) => confirmPendingSubscriptionCreate(vars), { + >({ + mutationFn: (vars) => confirmPendingSubscriptionCreate(vars), async onSuccess(data, variables, context) { // Handle 202 Accepted - show toast and skip query updates if (data && 'message' in data && !('slug' in data)) { diff --git a/apps/studio/data/subscriptions/org-subscription-query.ts b/apps/studio/data/subscriptions/org-subscription-query.ts index c2d068bbbec9d..f8747efb49b41 100644 --- a/apps/studio/data/subscriptions/org-subscription-query.ts +++ b/apps/studio/data/subscriptions/org-subscription-query.ts @@ -42,15 +42,13 @@ export const useOrgSubscriptionQuery = ( 'stripe.subscriptions' ) - return useQuery( - subscriptionKeys.orgSubscription(orgSlug), - ({ signal }) => getOrgSubscription({ orgSlug }, signal), - { - enabled: enabled && canReadSubscriptions && typeof orgSlug !== 'undefined', - staleTime: 60 * 60 * 1000, // 60 minutes - ...options, - } - ) + return useQuery({ + queryKey: subscriptionKeys.orgSubscription(orgSlug), + queryFn: ({ signal }) => getOrgSubscription({ orgSlug }, signal), + enabled: enabled && canReadSubscriptions && typeof orgSlug !== 'undefined', + staleTime: 60 * 60 * 1000, + ...options, + }) } export const useHasAccessToProjectLevelPermissions = (slug: string) => { diff --git a/apps/studio/data/subscriptions/org-subscription-update-mutation.ts b/apps/studio/data/subscriptions/org-subscription-update-mutation.ts index e819419678182..e6bbace4b160c 100644 --- a/apps/studio/data/subscriptions/org-subscription-update-mutation.ts +++ b/apps/studio/data/subscriptions/org-subscription-update-mutation.ts @@ -59,54 +59,52 @@ export const useOrgSubscriptionUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateOrgSubscription(vars), - { - async onSuccess(data, variables, context) { - const { slug } = variables + return useMutation({ + mutationFn: (vars) => updateOrgSubscription(vars), + async onSuccess(data, variables, context) { + const { slug } = variables - if (!data.pending_payment_intent_secret) { - // [Kevin] Backend can return stale data as it's waiting for the Stripe-sync to complete. Until that's solved in the backend - // we are going back to monkey here and delay the invalidation - await new Promise((resolve) => setTimeout(resolve, 2000)) + if (!data.pending_payment_intent_secret) { + // [Kevin] Backend can return stale data as it's waiting for the Stripe-sync to complete. Until that's solved in the backend + // we are going back to monkey here and delay the invalidation + await new Promise((resolve) => setTimeout(resolve, 2000)) - await Promise.all([ - queryClient.invalidateQueries(subscriptionKeys.orgSubscription(slug)), - queryClient.invalidateQueries(subscriptionKeys.orgPlans(slug)), - queryClient.invalidateQueries(usageKeys.orgUsage(slug)), - queryClient.invalidateQueries(invoicesKeys.orgUpcomingPreview(slug)), - queryClient.invalidateQueries(organizationKeys.detail(slug)), - queryClient.invalidateQueries(organizationKeys.list()), - ]) + await Promise.all([ + queryClient.invalidateQueries(subscriptionKeys.orgSubscription(slug)), + queryClient.invalidateQueries(subscriptionKeys.orgPlans(slug)), + queryClient.invalidateQueries(usageKeys.orgUsage(slug)), + queryClient.invalidateQueries(invoicesKeys.orgUpcomingPreview(slug)), + queryClient.invalidateQueries(organizationKeys.detail(slug)), + queryClient.invalidateQueries(organizationKeys.list()), + ]) - if (variables.paymentMethod) { - queryClient.setQueriesData(organizationKeys.paymentMethods(slug), (prev: any) => { - if (!prev) return prev - return { - ...prev, - defaultPaymentMethodId: variables.paymentMethod, - data: prev.data.map((pm: any) => ({ - ...pm, - is_default: pm.id === variables.paymentMethod, - })), - } - }) - } - } - - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(data.message, { - dismissible: true, - duration: 10_000, + if (variables.paymentMethod) { + queryClient.setQueriesData(organizationKeys.paymentMethods(slug), (prev: any) => { + if (!prev) return prev + return { + ...prev, + defaultPaymentMethodId: variables.paymentMethod, + data: prev.data.map((pm: any) => ({ + ...pm, + is_default: pm.id === variables.paymentMethod, + })), + } }) - } else { - onError(data, variables, context) } - }, - ...options, - } - ) + } + + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(data.message, { + dismissible: true, + duration: 10_000, + }) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/subscriptions/project-addon-remove-mutation.ts b/apps/studio/data/subscriptions/project-addon-remove-mutation.ts index 947d3015d9399..efd3ce5af9968 100644 --- a/apps/studio/data/subscriptions/project-addon-remove-mutation.ts +++ b/apps/studio/data/subscriptions/project-addon-remove-mutation.ts @@ -43,24 +43,22 @@ export const useProjectAddonRemoveMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => removeSubscriptionAddon(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - // [Joshen] Only invalidate addons, not subscriptions, as AddOn section in - // subscription page is using AddOn react query - await queryClient.invalidateQueries(subscriptionKeys.addons(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to remove addon: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => removeSubscriptionAddon(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + // [Joshen] Only invalidate addons, not subscriptions, as AddOn section in + // subscription page is using AddOn react query + await queryClient.invalidateQueries(subscriptionKeys.addons(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to remove addon: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/subscriptions/project-addon-update-mutation.ts b/apps/studio/data/subscriptions/project-addon-update-mutation.ts index 4064770aeee97..b963fd34ca3a2 100644 --- a/apps/studio/data/subscriptions/project-addon-update-mutation.ts +++ b/apps/studio/data/subscriptions/project-addon-update-mutation.ts @@ -50,22 +50,20 @@ export const useProjectAddonUpdateMutation = ({ > & { suppressToast?: boolean } = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateSubscriptionAddon(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(subscriptionKeys.addons(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update addon: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateSubscriptionAddon(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(subscriptionKeys.addons(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update addon: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/subscriptions/project-addons-query.ts b/apps/studio/data/subscriptions/project-addons-query.ts index 8e3375350a349..b92c843ae622f 100644 --- a/apps/studio/data/subscriptions/project-addons-query.ts +++ b/apps/studio/data/subscriptions/project-addons-query.ts @@ -34,12 +34,10 @@ export const useProjectAddonsQuery = ( { projectRef }: ProjectAddonsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - subscriptionKeys.addons(projectRef), - ({ signal }) => getProjectAddons({ projectRef }, signal), - { - enabled: enabled && IS_PLATFORM && typeof projectRef !== 'undefined', - staleTime: 60 * 60 * 1000, // 60 minutes - ...options, - } - ) + useQuery({ + queryKey: subscriptionKeys.addons(projectRef), + queryFn: ({ signal }) => getProjectAddons({ projectRef }, signal), + enabled: enabled && IS_PLATFORM && typeof projectRef !== 'undefined', + staleTime: 60 * 60 * 1000, + ...options, + }) diff --git a/apps/studio/data/support/generate-attachment-urls-mutation.ts b/apps/studio/data/support/generate-attachment-urls-mutation.ts index edd36078e7a55..5ab50a50b6a82 100644 --- a/apps/studio/data/support/generate-attachment-urls-mutation.ts +++ b/apps/studio/data/support/generate-attachment-urls-mutation.ts @@ -55,20 +55,18 @@ export const useGenerateAttachmentURLsMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => generateAttachmentURLs(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to generate attachment URLS: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => generateAttachmentURLs(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to generate attachment URLS: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/table-editor/table-editor-query.ts b/apps/studio/data/table-editor/table-editor-query.ts index 921149173c063..73a95b7bf3fe7 100644 --- a/apps/studio/data/table-editor/table-editor-query.ts +++ b/apps/studio/data/table-editor/table-editor-query.ts @@ -43,18 +43,16 @@ export const useTableEditorQuery = ( { projectRef, connectionString, id }: TableEditorVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - tableEditorKeys.tableEditor(projectRef, id), - ({ signal }) => getTableEditor({ projectRef, connectionString, id }, signal), - { - enabled: - enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined' && !isNaN(id), - refetchOnWindowFocus: false, - refetchOnMount: false, - staleTime: 5 * 60 * 1000, // 5 minutes - ...options, - } - ) + useQuery({ + queryKey: tableEditorKeys.tableEditor(projectRef, id), + queryFn: ({ signal }) => getTableEditor({ projectRef, connectionString, id }, signal), + enabled: + enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined' && !isNaN(id), + refetchOnWindowFocus: false, + refetchOnMount: false, + staleTime: 5 * 60 * 1000, + ...options, + }) export function prefetchTableEditor( client: QueryClient, diff --git a/apps/studio/data/table-rows/get-cell-value-mutation.ts b/apps/studio/data/table-rows/get-cell-value-mutation.ts index 0bcde7494bcc4..c18e319a94b77 100644 --- a/apps/studio/data/table-rows/get-cell-value-mutation.ts +++ b/apps/studio/data/table-rows/get-cell-value-mutation.ts @@ -47,20 +47,18 @@ export const useGetCellValueMutation = ({ UseMutationOptions, 'mutationFn' > = {}) => { - return useMutation( - (vars) => getCellValue(vars), - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(data.message) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => getCellValue(vars), + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(data.message) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/table-rows/table-row-create-mutation.ts b/apps/studio/data/table-rows/table-row-create-mutation.ts index f901c10ce8416..081d0cf4bc1e9 100644 --- a/apps/studio/data/table-rows/table-row-create-mutation.ts +++ b/apps/studio/data/table-rows/table-row-create-mutation.ts @@ -70,41 +70,39 @@ export const useTableRowCreateMutation = ({ const { mutate: sendEvent } = useSendEventMutation() const { data: org } = useSelectedOrganizationQuery() - return useMutation( - (vars) => createTableRow(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, table } = variables + return useMutation({ + mutationFn: (vars) => createTableRow(vars), + async onSuccess(data, variables, context) { + const { projectRef, table } = variables - // Track data insertion event - try { - sendEvent({ - action: 'table_data_added', - properties: { - method: 'table_editor', - schema_name: table.schema, - table_name: table.name, - }, - groups: { - project: projectRef, - ...(org?.slug && { organization: org.slug }), - }, - }) - } catch (error) { - console.error('Failed to track table data insertion event:', error) - } + // Track data insertion event + try { + sendEvent({ + action: 'table_data_added', + properties: { + method: 'table_editor', + schema_name: table.schema, + table_name: table.name, + }, + groups: { + project: projectRef, + ...(org?.slug && { organization: org.slug }), + }, + }) + } catch (error) { + console.error('Failed to track table data insertion event:', error) + } - await queryClient.invalidateQueries(tableRowKeys.tableRowsAndCount(projectRef, table.id)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(data.message) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await queryClient.invalidateQueries(tableRowKeys.tableRowsAndCount(projectRef, table.id)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(data.message) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/table-rows/table-row-delete-all-mutation.ts b/apps/studio/data/table-rows/table-row-delete-all-mutation.ts index 4948f1959574e..47eadc2fa94c0 100644 --- a/apps/studio/data/table-rows/table-row-delete-all-mutation.ts +++ b/apps/studio/data/table-rows/table-row-delete-all-mutation.ts @@ -72,22 +72,20 @@ export const useTableRowDeleteAllMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteAllTableRow(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, table } = variables - await queryClient.invalidateQueries(tableRowKeys.tableRowsAndCount(projectRef, table.id)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete all table rows: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteAllTableRow(vars), + async onSuccess(data, variables, context) { + const { projectRef, table } = variables + await queryClient.invalidateQueries(tableRowKeys.tableRowsAndCount(projectRef, table.id)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete all table rows: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/table-rows/table-row-delete-mutation.tsx b/apps/studio/data/table-rows/table-row-delete-mutation.tsx index bfe4d96c67dfe..16caac04c332b 100644 --- a/apps/studio/data/table-rows/table-row-delete-mutation.tsx +++ b/apps/studio/data/table-rows/table-row-delete-mutation.tsx @@ -72,69 +72,67 @@ export const useTableRowDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteTableRow(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, table } = variables - await queryClient.invalidateQueries(tableRowKeys.tableRowsAndCount(projectRef, table.id)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - const { table, rows } = variables - const isPkError = data.message.includes('Please add a primary key column') - const isFkError = data.message.includes('violates foreign key constraint') - const isMultipleRows = rows.length > 1 + return useMutation({ + mutationFn: (vars) => deleteTableRow(vars), + async onSuccess(data, variables, context) { + const { projectRef, table } = variables + await queryClient.invalidateQueries(tableRowKeys.tableRowsAndCount(projectRef, table.id)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + const { table, rows } = variables + const isPkError = data.message.includes('Please add a primary key column') + const isFkError = data.message.includes('violates foreign key constraint') + const isMultipleRows = rows.length > 1 - if (isFkError) { - const sourceTable = table.name - const referencingTable = data.message.split('on table ')[2].replaceAll('"', '') - const fkName = data.message - .split('foreign key constraint')[1] - .split('on table')[0] - .replaceAll('"', '') - const initialMessage = isMultipleRows - ? `Unable to delete rows as one of them is currently referenced by a foreign key constraint from the table \`${referencingTable}\`.` - : `Unable to delete row as it is currently referenced by a foreign key constraint from the table \`${referencingTable}\`.` - const resolutionCTA = `Set an on delete behavior on the foreign key relation \`${fkName}\` in the \`${referencingTable}\` table to automatically respond when row(s) are being deleted in the \`${sourceTable}\` table.` + if (isFkError) { + const sourceTable = table.name + const referencingTable = data.message.split('on table ')[2].replaceAll('"', '') + const fkName = data.message + .split('foreign key constraint')[1] + .split('on table')[0] + .replaceAll('"', '') + const initialMessage = isMultipleRows + ? `Unable to delete rows as one of them is currently referenced by a foreign key constraint from the table \`${referencingTable}\`.` + : `Unable to delete row as it is currently referenced by a foreign key constraint from the table \`${referencingTable}\`.` + const resolutionCTA = `Set an on delete behavior on the foreign key relation \`${fkName}\` in the \`${referencingTable}\` table to automatically respond when row(s) are being deleted in the \`${sourceTable}\` table.` - toast(initialMessage, { - description: , - action: ( -
- {/* [Joshen] Ideally we also are able to add this CTA but we can't guarantee this info without an on-demand fetch */} - {/* */} - + +
+ ), + }) + } else if (isPkError) { + toast('Unable to delete row(s) as table has no primary keys', { + description: ( +
+

+ Add a primary key column to your table first to serve as a unique identifier for + each row before updating or deleting the row. +

+
+
- ), - }) - } else if (isPkError) { - toast('Unable to delete row(s) as table has no primary keys', { - description: ( -
-

- Add a primary key column to your table first to serve as a unique identifier for - each row before updating or deleting the row. -

-
- -
-
- ), - }) - } else { - toast.error(`Failed to delete table row: ${data.message}`) - } +
+ ), + }) } else { - onError(data, variables, context) + toast.error(`Failed to delete table row: ${data.message}`) } - }, - ...options, - } - ) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/table-rows/table-row-truncate-mutation.ts b/apps/studio/data/table-rows/table-row-truncate-mutation.ts index 3427e92373032..9178163254725 100644 --- a/apps/studio/data/table-rows/table-row-truncate-mutation.ts +++ b/apps/studio/data/table-rows/table-row-truncate-mutation.ts @@ -46,22 +46,20 @@ export const useTableRowTruncateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => truncateTableRow(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, table } = variables - await queryClient.invalidateQueries(tableRowKeys.tableRowsAndCount(projectRef, table.id)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to truncate table row: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => truncateTableRow(vars), + async onSuccess(data, variables, context) { + const { projectRef, table } = variables + await queryClient.invalidateQueries(tableRowKeys.tableRowsAndCount(projectRef, table.id)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to truncate table row: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/table-rows/table-row-update-mutation.ts b/apps/studio/data/table-rows/table-row-update-mutation.ts index d05f679d01e4b..33b08d7e9c1fc 100644 --- a/apps/studio/data/table-rows/table-row-update-mutation.ts +++ b/apps/studio/data/table-rows/table-row-update-mutation.ts @@ -74,24 +74,22 @@ export const useTableRowUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateTableRow(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, table } = variables - await queryClient.invalidateQueries( - tableRowKeys.tableRows(projectRef, { table: { id: table.id } }) - ) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update table row: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateTableRow(vars), + async onSuccess(data, variables, context) { + const { projectRef, table } = variables + await queryClient.invalidateQueries( + tableRowKeys.tableRows(projectRef, { table: { id: table.id } }) + ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update table row: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/table-rows/table-rows-count-query.ts b/apps/studio/data/table-rows/table-rows-count-query.ts index fd888b8528c46..ccc5a00cb0825 100644 --- a/apps/studio/data/table-rows/table-rows-count-query.ts +++ b/apps/studio/data/table-rows/table-rows-count-query.ts @@ -148,13 +148,11 @@ export const useTableRowsCountQuery = ( }: UseQueryOptions = {} ) => { const queryClient = useQueryClient() - return useQuery( - tableRowKeys.tableRowsCount(projectRef, { table: { id: tableId }, ...args }), - ({ signal }) => + return useQuery({ + queryKey: tableRowKeys.tableRowsCount(projectRef, { table: { id: tableId }, ...args }), + queryFn: ({ signal }) => getTableRowsCount({ queryClient, projectRef, connectionString, tableId, ...args }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof tableId !== 'undefined', - ...options, - } - ) + enabled: enabled && typeof projectRef !== 'undefined' && typeof tableId !== 'undefined', + ...options, + }) } diff --git a/apps/studio/data/table-rows/table-rows-query.ts b/apps/studio/data/table-rows/table-rows-query.ts index a7807780735b3..4f9435c06efae 100644 --- a/apps/studio/data/table-rows/table-rows-query.ts +++ b/apps/studio/data/table-rows/table-rows-query.ts @@ -262,18 +262,16 @@ export const useTableRowsQuery = ( { enabled = true, ...options }: UseQueryOptions = {} ) => { const queryClient = useQueryClient() - return useQuery( - tableRowKeys.tableRows(projectRef, { + return useQuery({ + queryKey: tableRowKeys.tableRows(projectRef, { table: { id: tableId }, ...args, }), - ({ signal }) => + queryFn: ({ signal }) => getTableRows({ queryClient, projectRef, connectionString, tableId, ...args }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined' && typeof tableId !== 'undefined', - ...options, - } - ) + enabled: enabled && typeof projectRef !== 'undefined' && typeof tableId !== 'undefined', + ...options, + }) } export function prefetchTableRows( diff --git a/apps/studio/data/tables/table-create-mutation.ts b/apps/studio/data/tables/table-create-mutation.ts index cc81e596e8d1e..b894811cd1db5 100644 --- a/apps/studio/data/tables/table-create-mutation.ts +++ b/apps/studio/data/tables/table-create-mutation.ts @@ -41,26 +41,24 @@ export const useTableCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createTable(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, payload } = variables + return useMutation({ + mutationFn: (vars) => createTable(vars), + async onSuccess(data, variables, context) { + const { projectRef, payload } = variables - await Promise.all([ - queryClient.invalidateQueries(tableKeys.list(projectRef, payload.schema, true)), - queryClient.invalidateQueries(tableKeys.list(projectRef, payload.schema, false)), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create database table: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await Promise.all([ + queryClient.invalidateQueries(tableKeys.list(projectRef, payload.schema, true)), + queryClient.invalidateQueries(tableKeys.list(projectRef, payload.schema, false)), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create database table: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/tables/table-delete-mutation.ts b/apps/studio/data/tables/table-delete-mutation.ts index d23a994419a60..3934fb5036f26 100644 --- a/apps/studio/data/tables/table-delete-mutation.ts +++ b/apps/studio/data/tables/table-delete-mutation.ts @@ -50,29 +50,27 @@ export const useTableDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteTable(vars), - { - async onSuccess(data, variables, context) { - const { id, projectRef, schema } = variables - await Promise.all([ - queryClient.invalidateQueries(tableEditorKeys.tableEditor(projectRef, id)), - queryClient.invalidateQueries(tableKeys.list(projectRef, schema)), - queryClient.invalidateQueries(entityTypeKeys.list(projectRef)), - // invalidate all views from this schema - queryClient.invalidateQueries(viewKeys.listBySchema(projectRef, schema)), - ]) + return useMutation({ + mutationFn: (vars) => deleteTable(vars), + async onSuccess(data, variables, context) { + const { id, projectRef, schema } = variables + await Promise.all([ + queryClient.invalidateQueries(tableEditorKeys.tableEditor(projectRef, id)), + queryClient.invalidateQueries(tableKeys.list(projectRef, schema)), + queryClient.invalidateQueries(entityTypeKeys.list(projectRef)), + // invalidate all views from this schema + queryClient.invalidateQueries(viewKeys.listBySchema(projectRef, schema)), + ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete database table: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete database table: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/tables/table-retrieve-query.ts b/apps/studio/data/tables/table-retrieve-query.ts index f8bffcd851f89..34f9f173f10b3 100644 --- a/apps/studio/data/tables/table-retrieve-query.ts +++ b/apps/studio/data/tables/table-retrieve-query.ts @@ -41,9 +41,10 @@ export const useTablesQuery = ( ...options }: UseQueryOptions = {} ) => { - return useQuery( - tableKeys.retrieve(projectRef, name, schema), - ({ signal }) => getTable({ projectRef, connectionString, name, schema }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + return useQuery({ + queryKey: tableKeys.retrieve(projectRef, name, schema), + queryFn: ({ signal }) => getTable({ projectRef, connectionString, name, schema }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) } diff --git a/apps/studio/data/tables/table-update-mutation.ts b/apps/studio/data/tables/table-update-mutation.ts index 69ec11ef3e3fd..b62e56a79a4c2 100644 --- a/apps/studio/data/tables/table-update-mutation.ts +++ b/apps/studio/data/tables/table-update-mutation.ts @@ -52,26 +52,24 @@ export const useTableUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateTable(vars), - { - async onSuccess(data, variables, context) { - const { projectRef, schema, id } = variables - await Promise.all([ - queryClient.invalidateQueries(tableEditorKeys.tableEditor(projectRef, id)), - queryClient.invalidateQueries(tableKeys.list(projectRef, schema)), - queryClient.invalidateQueries(lintKeys.lint(projectRef)), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update database table: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateTable(vars), + async onSuccess(data, variables, context) { + const { projectRef, schema, id } = variables + await Promise.all([ + queryClient.invalidateQueries(tableEditorKeys.tableEditor(projectRef, id)), + queryClient.invalidateQueries(tableKeys.list(projectRef, schema)), + queryClient.invalidateQueries(lintKeys.lint(projectRef)), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update database table: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/tables/tables-query.ts b/apps/studio/data/tables/tables-query.ts index af715ea5b60ae..5e9c35895efb3 100644 --- a/apps/studio/data/tables/tables-query.ts +++ b/apps/studio/data/tables/tables-query.ts @@ -74,11 +74,13 @@ export const useTablesQuery = ( { projectRef, connectionString, schema, includeColumns }: TablesVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => { - return useQuery( - tableKeys.list(projectRef, schema, includeColumns), - ({ signal }) => getTables({ projectRef, connectionString, schema, includeColumns }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', ...options } - ) + return useQuery({ + queryKey: tableKeys.list(projectRef, schema, includeColumns), + queryFn: ({ signal }) => + getTables({ projectRef, connectionString, schema, includeColumns }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) } /** diff --git a/apps/studio/data/telemetry/send-event-mutation.ts b/apps/studio/data/telemetry/send-event-mutation.ts index 621e1aaa6f52c..1968853b7d2ef 100644 --- a/apps/studio/data/telemetry/send-event-mutation.ts +++ b/apps/studio/data/telemetry/send-event-mutation.ts @@ -29,22 +29,20 @@ export const useSendEventMutation = ({ }: Omit, 'mutationFn'> = {}) => { const router = useRouter() - return useMutation( - (event) => { + return useMutation({ + mutationFn: (event) => { return sendEvent({ event, pathname: router.pathname }) }, - { - async onSuccess(data, variables, context) { - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - console.error(`Failed to send Telemetry event: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + async onSuccess(data, variables, context) { + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + console.error(`Failed to send Telemetry event: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/telemetry/send-reset-mutation.ts b/apps/studio/data/telemetry/send-reset-mutation.ts index 73ce7964570d2..b22b19a3880ef 100644 --- a/apps/studio/data/telemetry/send-reset-mutation.ts +++ b/apps/studio/data/telemetry/send-reset-mutation.ts @@ -19,7 +19,8 @@ export const useSendResetMutation = ({ onError, ...options }: Omit, 'mutationFn'> = {}) => { - return useMutation(() => sendReset(), { + return useMutation({ + mutationFn: () => sendReset(), async onSuccess(data, variables, context) { await onSuccess?.(data, variables, context) }, diff --git a/apps/studio/data/third-party-auth/integration-create-mutation.ts b/apps/studio/data/third-party-auth/integration-create-mutation.ts index 1e240b6bbaa46..520e63f62bc73 100644 --- a/apps/studio/data/third-party-auth/integration-create-mutation.ts +++ b/apps/studio/data/third-party-auth/integration-create-mutation.ts @@ -47,8 +47,8 @@ export const useCreateThirdPartyAuthIntegrationMutation = ({ > = {}) => { const queryClient = useQueryClient() return useMutation( - (vars) => createThirdPartyIntegration(vars), { + mutationFn: (vars) => createThirdPartyIntegration(vars), async onSuccess(data, variables, context) { const { projectRef } = variables await queryClient.invalidateQueries(keys.integrations(projectRef)) diff --git a/apps/studio/data/third-party-auth/integration-delete-mutation.ts b/apps/studio/data/third-party-auth/integration-delete-mutation.ts index 16312b8125508..7ee48bdf825fd 100644 --- a/apps/studio/data/third-party-auth/integration-delete-mutation.ts +++ b/apps/studio/data/third-party-auth/integration-delete-mutation.ts @@ -45,7 +45,8 @@ export const useDeleteThirdPartyAuthIntegrationMutation = ({ DeleteThirdPartyAuthIntegrationData, ResponseError, DeleteThirdPartyAuthIntegrationVariables - >((vars) => deleteThirdPartyIntegration(vars), { + >({ + mutationFn: (vars) => deleteThirdPartyIntegration(vars), async onSuccess(data, variables, context) { const { projectRef } = variables await queryClient.invalidateQueries(keys.integrations(projectRef)) diff --git a/apps/studio/data/third-party-auth/integrations-query.ts b/apps/studio/data/third-party-auth/integrations-query.ts index 19b36bbd27a12..04d7e4a3d111d 100644 --- a/apps/studio/data/third-party-auth/integrations-query.ts +++ b/apps/studio/data/third-party-auth/integrations-query.ts @@ -36,11 +36,9 @@ export const useThirdPartyAuthIntegrationsQuery = = {} ) => - useQuery( - keys.integrations(projectRef), - ({ signal }) => getThirdPartyAuthIntegrations({ projectRef }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: keys.integrations(projectRef), + queryFn: ({ signal }) => getThirdPartyAuthIntegrations({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/usage/org-usage-query.ts b/apps/studio/data/usage/org-usage-query.ts index 4110c6660c2a0..2bfbfafb983d5 100644 --- a/apps/studio/data/usage/org-usage-query.ts +++ b/apps/studio/data/usage/org-usage-query.ts @@ -39,12 +39,10 @@ export const useOrgUsageQuery = ( { orgSlug, projectRef, start, end }: OrgUsageVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - usageKeys.orgUsage(orgSlug, projectRef, start?.toISOString(), end?.toISOString()), - ({ signal }) => getOrgUsage({ orgSlug, projectRef, start, end }, signal), - { - enabled: enabled && IS_PLATFORM && typeof orgSlug !== 'undefined', - staleTime: 1000 * 60 * 60, // 60 mins, underlying usage data only refreshes once an hour, so safe to cache for a while - ...options, - } - ) + useQuery({ + queryKey: usageKeys.orgUsage(orgSlug, projectRef, start?.toISOString(), end?.toISOString()), + queryFn: ({ signal }) => getOrgUsage({ orgSlug, projectRef, start, end }, signal), + enabled: enabled && IS_PLATFORM && typeof orgSlug !== 'undefined', + staleTime: 1000 * 60 * 60, + ...options, + }) diff --git a/apps/studio/data/usage/resource-warnings-query.ts b/apps/studio/data/usage/resource-warnings-query.ts index cf69871c80b0f..8304d8d5ca4d9 100644 --- a/apps/studio/data/usage/resource-warnings-query.ts +++ b/apps/studio/data/usage/resource-warnings-query.ts @@ -40,13 +40,11 @@ export const useResourceWarningsQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - usageKeys.resourceWarnings(variables.slug, variables.ref), - ({ signal }) => getResourceWarnings(variables, signal), - { - enabled: - IS_PLATFORM && enabled && (variables.ref !== undefined || variables.slug !== undefined), - staleTime: 1000 * 60 * 60, // default 60 minutes - ...options, - } - ) + useQuery({ + queryKey: usageKeys.resourceWarnings(variables.slug, variables.ref), + queryFn: ({ signal }) => getResourceWarnings(variables, signal), + enabled: + IS_PLATFORM && enabled && (variables.ref !== undefined || variables.slug !== undefined), + staleTime: 1000 * 60 * 60, + ...options, + }) diff --git a/apps/studio/data/utils/deployment-commit-query.ts b/apps/studio/data/utils/deployment-commit-query.ts index 67403cf23f509..0e243be079425 100644 --- a/apps/studio/data/utils/deployment-commit-query.ts +++ b/apps/studio/data/utils/deployment-commit-query.ts @@ -14,10 +14,8 @@ export const useDeploymentCommitQuery = ({ enabled = true, ...options }: UseQueryOptions = {}) => - useQuery( - ['deployment-commit'], - ({ signal }) => getDeploymentCommit(signal), - { - ...options, - } - ) + useQuery({ + queryKey: ['deployment-commit'], + queryFn: ({ signal }) => getDeploymentCommit(signal), + ...options, + }) diff --git a/apps/studio/data/vault/vault-secret-create-mutation.ts b/apps/studio/data/vault/vault-secret-create-mutation.ts index b66d5747ab570..40d4579805698 100644 --- a/apps/studio/data/vault/vault-secret-create-mutation.ts +++ b/apps/studio/data/vault/vault-secret-create-mutation.ts @@ -41,22 +41,20 @@ export const useVaultSecretCreateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => createVaultSecret(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(vaultSecretsKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to create secret: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => createVaultSecret(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(vaultSecretsKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to create secret: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/vault/vault-secret-decrypted-value-query.ts b/apps/studio/data/vault/vault-secret-decrypted-value-query.ts index f64d00145cf78..4657fd2b31cbd 100644 --- a/apps/studio/data/vault/vault-secret-decrypted-value-query.ts +++ b/apps/studio/data/vault/vault-secret-decrypted-value-query.ts @@ -57,17 +57,15 @@ export const useVaultSecretDecryptedValueQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - vaultSecretsKeys.getDecryptedValue(projectRef, id), - ({ signal }) => getDecryptedValue({ projectRef, connectionString, id }, signal), - { - select(data) { - return (data[0]?.decrypted_secret ?? '') as TData - }, - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: vaultSecretsKeys.getDecryptedValue(projectRef, id), + queryFn: ({ signal }) => getDecryptedValue({ projectRef, connectionString, id }, signal), + select(data) { + return (data[0]?.decrypted_secret ?? '') as TData + }, + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) // [Joshen] Considering to consolidate fetching single and multiple decrypted values by just passing in a string array // This is currently used in ImportForeignSchemaDialog, but reckon EditWrapperSheet can use this too to replace the useEffect on L153 diff --git a/apps/studio/data/vault/vault-secret-delete-mutation.ts b/apps/studio/data/vault/vault-secret-delete-mutation.ts index afbfd860ad3ac..e1d6aaa5d6d7f 100644 --- a/apps/studio/data/vault/vault-secret-delete-mutation.ts +++ b/apps/studio/data/vault/vault-secret-delete-mutation.ts @@ -34,22 +34,20 @@ export const useVaultSecretDeleteMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => deleteVaultSecret(vars), - { - async onSuccess(data, variables, context) { - const { projectRef } = variables - await queryClient.invalidateQueries(vaultSecretsKeys.list(projectRef)) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to delete key: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => deleteVaultSecret(vars), + async onSuccess(data, variables, context) { + const { projectRef } = variables + await queryClient.invalidateQueries(vaultSecretsKeys.list(projectRef)) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to delete key: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/vault/vault-secret-update-mutation.ts b/apps/studio/data/vault/vault-secret-update-mutation.ts index 0d44f3f7b333c..ee33ece65a397 100644 --- a/apps/studio/data/vault/vault-secret-update-mutation.ts +++ b/apps/studio/data/vault/vault-secret-update-mutation.ts @@ -44,25 +44,23 @@ export const useVaultSecretUpdateMutation = ({ > = {}) => { const queryClient = useQueryClient() - return useMutation( - (vars) => updateVaultSecret(vars), - { - async onSuccess(data, variables, context) { - const { id, projectRef } = variables - await Promise.all([ - queryClient.removeQueries(vaultSecretsKeys.getDecryptedValue(projectRef, id)), - queryClient.invalidateQueries(vaultSecretsKeys.list(projectRef)), - ]) - await onSuccess?.(data, variables, context) - }, - async onError(data, variables, context) { - if (onError === undefined) { - toast.error(`Failed to update key: ${data.message}`) - } else { - onError(data, variables, context) - } - }, - ...options, - } - ) + return useMutation({ + mutationFn: (vars) => updateVaultSecret(vars), + async onSuccess(data, variables, context) { + const { id, projectRef } = variables + await Promise.all([ + queryClient.removeQueries(vaultSecretsKeys.getDecryptedValue(projectRef, id)), + queryClient.invalidateQueries(vaultSecretsKeys.list(projectRef)), + ]) + await onSuccess?.(data, variables, context) + }, + async onError(data, variables, context) { + if (onError === undefined) { + toast.error(`Failed to update key: ${data.message}`) + } else { + onError(data, variables, context) + } + }, + ...options, + }) } diff --git a/apps/studio/data/vault/vault-secrets-query.ts b/apps/studio/data/vault/vault-secrets-query.ts index 23d328489e1b3..93ae6537e5538 100644 --- a/apps/studio/data/vault/vault-secrets-query.ts +++ b/apps/studio/data/vault/vault-secrets-query.ts @@ -39,11 +39,9 @@ export const useVaultSecretsQuery = ( { projectRef, connectionString }: VaultSecretsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - vaultSecretsKeys.list(projectRef), - ({ signal }) => getVaultSecrets({ projectRef, connectionString }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - ...options, - } - ) + useQuery({ + queryKey: vaultSecretsKeys.list(projectRef), + queryFn: ({ signal }) => getVaultSecrets({ projectRef, connectionString }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + ...options, + }) diff --git a/apps/studio/data/views/views-query.ts b/apps/studio/data/views/views-query.ts index 884dda527e916..e271aa74546b0 100644 --- a/apps/studio/data/views/views-query.ts +++ b/apps/studio/data/views/views-query.ts @@ -47,14 +47,10 @@ export const useViewsQuery = ( { projectRef, connectionString, schema }: ViewsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - schema ? viewKeys.listBySchema(projectRef, schema) : viewKeys.list(projectRef), - ({ signal }) => getViews({ projectRef, connectionString, schema }, signal), - { - enabled: enabled && typeof projectRef !== 'undefined', - // We're using a staleTime of 0 here because the only way to create a - // view is via SQL, which we don't know about - staleTime: 0, - ...options, - } - ) + useQuery({ + queryKey: schema ? viewKeys.listBySchema(projectRef, schema) : viewKeys.list(projectRef), + queryFn: ({ signal }) => getViews({ projectRef, connectionString, schema }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + staleTime: 0, + ...options, + }) diff --git a/apps/studio/data/workflow-runs/workflow-run-logs-query.ts b/apps/studio/data/workflow-runs/workflow-run-logs-query.ts index 0e51abd0c8c43..b2ee250781e33 100644 --- a/apps/studio/data/workflow-runs/workflow-run-logs-query.ts +++ b/apps/studio/data/workflow-runs/workflow-run-logs-query.ts @@ -44,8 +44,10 @@ export const useWorkflowRunLogsQuery = ( ...options }: UseQueryOptions = {} ) => - useQuery( - workflowRunKeys.list(workflowRunId), - ({ signal }) => getWorkflowRunLogs({ workflowRunId }, signal), - { enabled: enabled && typeof workflowRunId !== 'undefined', staleTime: 0, ...options } - ) + useQuery({ + queryKey: workflowRunKeys.list(workflowRunId), + queryFn: ({ signal }) => getWorkflowRunLogs({ workflowRunId }, signal), + enabled: enabled && typeof workflowRunId !== 'undefined', + staleTime: 0, + ...options, + }) diff --git a/apps/studio/data/workflow-runs/workflow-run-query.ts b/apps/studio/data/workflow-runs/workflow-run-query.ts index e2164d1ec0df8..7b76abb693ba2 100644 --- a/apps/studio/data/workflow-runs/workflow-run-query.ts +++ b/apps/studio/data/workflow-runs/workflow-run-query.ts @@ -41,12 +41,10 @@ export const useWorkflowRunQuery = ( { projectRef, workflowRunId }: WorkflowRunVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - workflowRunKeys.detail(projectRef, workflowRunId), - ({ signal }) => getWorkflowRun({ workflowRunId }, signal), - { - enabled: enabled && typeof workflowRunId !== 'undefined', - staleTime: 0, - ...options, - } - ) + useQuery({ + queryKey: workflowRunKeys.detail(projectRef, workflowRunId), + queryFn: ({ signal }) => getWorkflowRun({ workflowRunId }, signal), + enabled: enabled && typeof workflowRunId !== 'undefined', + staleTime: 0, + ...options, + }) diff --git a/apps/studio/data/workflow-runs/workflow-runs-query.ts b/apps/studio/data/workflow-runs/workflow-runs-query.ts index 564dea7240aeb..c907eef42ab77 100644 --- a/apps/studio/data/workflow-runs/workflow-runs-query.ts +++ b/apps/studio/data/workflow-runs/workflow-runs-query.ts @@ -30,8 +30,10 @@ export const useWorkflowRunsQuery = ( { projectRef }: WorkflowRunsVariables, { enabled = true, ...options }: UseQueryOptions = {} ) => - useQuery( - workflowRunKeys.list(projectRef), - ({ signal }) => getWorkflowRuns({ projectRef }, signal), - { enabled: enabled && typeof projectRef !== 'undefined', staleTime: 0, ...options } - ) + useQuery({ + queryKey: workflowRunKeys.list(projectRef), + queryFn: ({ signal }) => getWorkflowRuns({ projectRef }, signal), + enabled: enabled && typeof projectRef !== 'undefined', + staleTime: 0, + ...options, + }) diff --git a/apps/studio/hooks/analytics/useDbQuery.tsx b/apps/studio/hooks/analytics/useDbQuery.tsx index 64bdbcf2db147..519fdfba2962c 100644 --- a/apps/studio/hooks/analytics/useDbQuery.tsx +++ b/apps/studio/hooks/analytics/useDbQuery.tsx @@ -53,9 +53,16 @@ const useDbQuery = ({ isLoading, isRefetching, refetch, - } = useQuery( - ['projects', project?.ref, 'db', { ...params, sql: resolvedSql, identifier }, where, orderBy], - ({ signal }) => { + } = useQuery({ + queryKey: [ + 'projects', + project?.ref, + 'db', + { ...params, sql: resolvedSql, identifier }, + where, + orderBy, + ], + queryFn: ({ signal }) => { return executeSql( { projectRef: project?.ref, @@ -65,12 +72,10 @@ const useDbQuery = ({ signal ).then((res) => res.result) as Promise }, - { - enabled: Boolean(resolvedSql), - refetchOnWindowFocus: false, - refetchOnReconnect: false, - } - ) + enabled: Boolean(resolvedSql), + refetchOnWindowFocus: false, + refetchOnReconnect: false, + }) const error = rqError || (typeof data === 'object' ? data?.error : '') return { diff --git a/apps/studio/hooks/analytics/useLogsPreview.tsx b/apps/studio/hooks/analytics/useLogsPreview.tsx index 27a62b248f21b..8f6bdde076190 100644 --- a/apps/studio/hooks/analytics/useLogsPreview.tsx +++ b/apps/studio/hooks/analytics/useLogsPreview.tsx @@ -169,9 +169,9 @@ function useLogsPreview({ [projectRef, countQuerySql, latestRefresh, timestampEnd, table, mergedFilters] ) - const { data: countData } = useQuery( - countQueryKey, - async ({ signal }) => { + const { data: countData } = useQuery({ + queryKey: countQueryKey, + queryFn: async ({ signal }) => { const { data, error } = await get(`/platform/projects/{ref}/analytics/endpoints/logs.all`, { params: { path: { ref: projectRef }, @@ -189,12 +189,10 @@ function useLogsPreview({ return data as unknown as Count }, - { - refetchOnWindowFocus: false, - refetchInterval: 60000, - enabled: !error && data && data?.pages?.length > 0 ? true : false, - } - ) + refetchOnWindowFocus: false, + refetchInterval: 60000, + enabled: !error && data && data?.pages?.length > 0 ? true : false, + }) const newCount = countData?.result?.[0]?.count ?? 0 @@ -217,9 +215,9 @@ function useLogsPreview({ [projectRef, chartQuery, timestampStart, timestampEnd] ) - const { data: eventChartResponse, refetch: refreshEventChart } = useQuery( - chartQueryKey, - async ({ signal }) => { + const { data: eventChartResponse, refetch: refreshEventChart } = useQuery({ + queryKey: chartQueryKey, + queryFn: async ({ signal }) => { const { data, error } = await get(`/platform/projects/{ref}/analytics/endpoints/logs.all`, { params: { path: { ref: projectRef }, @@ -237,8 +235,8 @@ function useLogsPreview({ return data as unknown as EventChart }, - { refetchOnWindowFocus: false } - ) + refetchOnWindowFocus: false, + }) const refresh = useCallback(async () => { setLatestRefresh(new Date().toISOString()) diff --git a/apps/studio/hooks/analytics/useLogsQuery.tsx b/apps/studio/hooks/analytics/useLogsQuery.tsx index 0adedd2129244..646ba8c7f9895 100644 --- a/apps/studio/hooks/analytics/useLogsQuery.tsx +++ b/apps/studio/hooks/analytics/useLogsQuery.tsx @@ -70,9 +70,9 @@ const useLogsQuery = ( isLoading, isRefetching, refetch, - } = useQuery( - ['projects', projectRef, 'logs', params], - async ({ signal }) => { + } = useQuery({ + queryKey: ['projects', projectRef, 'logs', params], + queryFn: async ({ signal }) => { const { data, error } = await get(`/platform/projects/{ref}/analytics/endpoints/logs.all`, { params: { path: { ref: projectRef }, @@ -86,11 +86,9 @@ const useLogsQuery = ( return data as unknown as Logs }, - { - enabled: _enabled, - refetchOnWindowFocus: false, - } - ) + enabled: _enabled, + refetchOnWindowFocus: false, + }) let error: null | string | object = rqError ? (rqError as any).message : null diff --git a/apps/studio/hooks/analytics/useProjectUsageStats.tsx b/apps/studio/hooks/analytics/useProjectUsageStats.tsx index 9ac129a49eeba..78021bff7c6dc 100644 --- a/apps/studio/hooks/analytics/useProjectUsageStats.tsx +++ b/apps/studio/hooks/analytics/useProjectUsageStats.tsx @@ -68,9 +68,9 @@ function useProjectUsageStats({ [projectRef, chartQuery, timestampStart, timestampEnd, table] ) - const { data: eventChartResponse, refetch: refreshEventChart } = useQuery( - chartQueryKey, - async ({ signal }) => { + const { data: eventChartResponse, refetch: refreshEventChart } = useQuery({ + queryKey: chartQueryKey, + queryFn: async ({ signal }) => { const { data, error } = await get(`/platform/projects/{ref}/analytics/endpoints/logs.all`, { params: { path: { ref: projectRef }, @@ -88,11 +88,9 @@ function useProjectUsageStats({ return data as unknown as EventChart }, - { - refetchOnWindowFocus: false, - enabled: typeof projectRef !== 'undefined', - } - ) + refetchOnWindowFocus: false, + enabled: typeof projectRef !== 'undefined', + }) const normalizedEventChartData = useTimeseriesUnixToIso( eventChartResponse?.result ?? [], diff --git a/apps/studio/hooks/analytics/useSingleLog.tsx b/apps/studio/hooks/analytics/useSingleLog.tsx index 6e0dbe9cc50d6..bb4156e3f6c34 100644 --- a/apps/studio/hooks/analytics/useSingleLog.tsx +++ b/apps/studio/hooks/analytics/useSingleLog.tsx @@ -44,9 +44,9 @@ function useSingleLog({ isLoading, isRefetching, refetch, - } = useQuery( - ['projects', projectRef, 'single-log', id, queryType], - async ({ signal }) => { + } = useQuery({ + queryKey: ['projects', projectRef, 'single-log', id, queryType], + queryFn: async ({ signal }) => { const { data, error } = await get(`/platform/projects/{ref}/analytics/endpoints/logs.all`, { params: { path: { ref: projectRef }, @@ -60,13 +60,11 @@ function useSingleLog({ return data as unknown as Logs }, - { - enabled, - refetchOnWindowFocus: false, - refetchOnMount: false, - refetchOnReconnect: false, - } - ) + enabled, + refetchOnWindowFocus: false, + refetchOnMount: false, + refetchOnReconnect: false, + }) let error: null | string | object = rcError ? (rcError as any).message : null const result = data?.result ? data.result[0] : undefined diff --git a/apps/studio/hooks/misc/useLocalStorage.ts b/apps/studio/hooks/misc/useLocalStorage.ts index 9df2b0de56f66..b9bb8329b9e21 100644 --- a/apps/studio/hooks/misc/useLocalStorage.ts +++ b/apps/studio/hooks/misc/useLocalStorage.ts @@ -64,18 +64,21 @@ export function useLocalStorageQuery(key: string, initialValue: T) { isSuccess, isLoading, isError, - } = useQuery(queryKey, () => { - if (typeof window === 'undefined') { - return initialValue - } + } = useQuery({ + queryKey, + queryFn: () => { + if (typeof window === 'undefined') { + return initialValue + } - const item = window.localStorage.getItem(key) + const item = window.localStorage.getItem(key) - if (!item) { - return initialValue - } + if (!item) { + return initialValue + } - return JSON.parse(item) as T + return JSON.parse(item) as T + }, }) const setValue: Dispatch> = (value) => { diff --git a/apps/studio/pages/new/[slug].tsx b/apps/studio/pages/new/[slug].tsx index d177c1220a25a..3dc60cf8e8fbd 100644 --- a/apps/studio/pages/new/[slug].tsx +++ b/apps/studio/pages/new/[slug].tsx @@ -1,35 +1,39 @@ import { zodResolver } from '@hookform/resolvers/zod' import { PermissionAction } from '@supabase/shared-types/out/constants' -import { debounce } from 'lodash' import Link from 'next/link' import { useRouter } from 'next/router' -import { PropsWithChildren, useEffect, useMemo, useRef, useState } from 'react' +import { PropsWithChildren, useEffect, useMemo, useState } from 'react' import { useForm } from 'react-hook-form' import { toast } from 'sonner' import { z } from 'zod' -import { PopoverSeparator } from '@ui/components/shadcn/ui/popover' import { LOCAL_STORAGE_KEYS, useFlag, useParams } from 'common' -import { NotOrganizationOwnerWarning } from 'components/interfaces/Organization/NewProject' -import { FreeProjectLimitWarning } from 'components/interfaces/Organization/NewProject/FreeProjectLimitWarning' -import { OrgNotFound } from 'components/interfaces/Organization/OrgNotFound' import { AdvancedConfiguration } from 'components/interfaces/ProjectCreation/AdvancedConfiguration' +import { CloudProviderSelector } from 'components/interfaces/ProjectCreation/CloudProviderSelector' +import { ComputeSizeSelector } from 'components/interfaces/ProjectCreation/ComputeSizeSelector' +import { CustomPostgresVersionInput } from 'components/interfaces/ProjectCreation/CustomPostgresVersionInput' +import { DatabasePasswordInput } from 'components/interfaces/ProjectCreation/DatabasePasswordInput' +import { DisabledWarningDueToIncident } from 'components/interfaces/ProjectCreation/DisabledWarningDueToIncident' +import { FreeProjectLimitWarning } from 'components/interfaces/ProjectCreation/FreeProjectLimitWarning' +import { OrganizationSelector } from 'components/interfaces/ProjectCreation/OrganizationSelector' import { extractPostgresVersionDetails, PostgresVersionSelector, } from 'components/interfaces/ProjectCreation/PostgresVersionSelector' -import { SPECIAL_CHARS_REGEX } from 'components/interfaces/ProjectCreation/ProjectCreation.constants' -import { smartRegionToExactRegion } from 'components/interfaces/ProjectCreation/ProjectCreation.utils' +import { sizes } from 'components/interfaces/ProjectCreation/ProjectCreation.constants' +import { FormSchema } from 'components/interfaces/ProjectCreation/ProjectCreation.schema' +import { + instanceLabel, + smartRegionToExactRegion, +} from 'components/interfaces/ProjectCreation/ProjectCreation.utils' +import { ProjectCreationFooter } from 'components/interfaces/ProjectCreation/ProjectCreationFooter' +import { ProjectNameInput } from 'components/interfaces/ProjectCreation/ProjectNameInput' import { RegionSelector } from 'components/interfaces/ProjectCreation/RegionSelector' import { SecurityOptions } from 'components/interfaces/ProjectCreation/SecurityOptions' -import { SpecialSymbolsCallout } from 'components/interfaces/ProjectCreation/SpecialSymbolsCallout' import DefaultLayout from 'components/layouts/DefaultLayout' import { WizardLayoutWithoutAuth } from 'components/layouts/WizardLayout' -import DisabledWarningDueToIncident from 'components/ui/DisabledWarningDueToIncident' -import { InlineLink } from 'components/ui/InlineLink' import Panel from 'components/ui/Panel' import PartnerManagedResource from 'components/ui/PartnerManagedResource' -import PasswordStrengthBar from 'components/ui/PasswordStrengthBar' import { useAvailableOrioleImageVersion } from 'data/config/project-creation-postgres-versions-query' import { useOverdueInvoicesQuery } from 'data/invoices/invoices-overdue-query' import { useDefaultRegionQuery } from 'data/misc/get-default-region-query' @@ -43,93 +47,30 @@ import { ProjectCreateVariables, useProjectCreateMutation, } from 'data/projects/project-create-mutation' -import { useCustomContent } from 'hooks/custom-content/useCustomContent' import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions' import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled' import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage' import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization' import { withAuth } from 'hooks/misc/withAuth' -import { getCloudProviderArchitecture } from 'lib/cloudprovider-utils' import { - AWS_REGIONS_DEFAULT, DEFAULT_MINIMUM_PASSWORD_STRENGTH, DOCS_URL, - FLY_REGIONS_DEFAULT, MANAGED_BY, PROJECT_STATUS, PROVIDERS, useDefaultProvider, } from 'lib/constants' -import passwordStrength from 'lib/password-strength' -import { generateStrongPassword } from 'lib/project' import { useTrack } from 'lib/telemetry/track' import { AWS_REGIONS, type CloudProvider } from 'shared-data' import type { NextPageWithLayout } from 'types' -import { - Badge, - Button, - Form_Shadcn_, - FormControl_Shadcn_, - FormField_Shadcn_, - Input_Shadcn_, - Select_Shadcn_, - SelectContent_Shadcn_, - SelectGroup_Shadcn_, - SelectItem_Shadcn_, - SelectTrigger_Shadcn_, - SelectValue_Shadcn_, - Table, - TableBody, - TableCell, - TableHead, - TableHeader, - TableRow, -} from 'ui' +import { Button, Form_Shadcn_, FormField_Shadcn_ } from 'ui' import { Admonition } from 'ui-patterns/admonition' -import { Input } from 'ui-patterns/DataInputs/Input' import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal' -import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' -import { InfoTooltip } from 'ui-patterns/info-tooltip' - -// [Joshen] This page is getting rather big and complex, let's aim to break this down into smaller components - -const sizes: DesiredInstanceSize[] = ['micro', 'small', 'medium'] const sizesWithNoCostConfirmationRequired: DesiredInstanceSize[] = ['micro', 'small'] -const FormSchema = z.object({ - organization: z.string({ - required_error: 'Please select an organization', - }), - projectName: z - .string() - .trim() - .min(1, 'Please enter a project name.') // Required field check - .min(3, 'Project name must be at least 3 characters long.') // Minimum length check - .max(64, 'Project name must be no longer than 64 characters.'), // Maximum length check - postgresVersion: z.string({ - required_error: 'Please enter a Postgres version.', - }), - dbRegion: z.string({ - required_error: 'Please select a region.', - }), - cloudProvider: z.string({ - required_error: 'Please select a cloud provider.', - }), - dbPassStrength: z.number(), - dbPass: z - .string({ required_error: 'Please enter a database password.' }) - .min(1, 'Password is required.'), - instanceSize: z.string().optional(), - dataApi: z.boolean(), - useApiSchema: z.boolean(), - postgresVersionSelection: z.string(), - useOrioleDb: z.boolean(), -}) - -export type CreateProjectForm = z.infer - const Wizard: NextPageWithLayout = () => { + const track = useTrack() const router = useRouter() const { slug, projectName } = useParams() const defaultProvider = useDefaultProvider() @@ -143,6 +84,7 @@ const Wizard: NextPageWithLayout = () => { '' ) const { can: isAdmin } = useAsyncCheckPermissions(PermissionAction.CREATE, 'projects') + const showAdvancedConfig = useIsFeatureEnabled('project_creation:show_advanced_config') const smartRegionEnabled = useFlag('enableSmartRegion') const projectCreationDisabled = useFlag('disableProjectCreationAndUpdate') @@ -150,11 +92,9 @@ const Wizard: NextPageWithLayout = () => { const cloudProviderEnabled = useFlag('enableFlyCloudProvider') const isHomeNew = useFlag('homeNew') - const showAdvancedConfig = useIsFeatureEnabled('project_creation:show_advanced_config') - const { infraCloudProviders: validCloudProviders } = useCustomContent(['infra:cloud_providers']) - const showNonProdFields = process.env.NEXT_PUBLIC_ENVIRONMENT !== 'prod' const isManagedByVercel = currentOrg?.managed_by === 'vercel-marketplace' + const isNotOnTeamOrEnterprisePlan = !['team', 'enterprise'].includes(currentOrg?.plan.id ?? '') // This is to make the database.new redirect work correctly. The database.new redirect should be set to supabase.com/dashboard/new/last-visited-org if (slug === 'last-visited-org') { @@ -171,8 +111,6 @@ const Wizard: NextPageWithLayout = () => { const [isComputeCostsConfirmationModalVisible, setIsComputeCostsConfirmationModalVisible] = useState(false) - const track = useTrack() - FormSchema.superRefine(({ dbPassStrength }, refinementContext) => { if (dbPassStrength < DEFAULT_MINIMUM_PASSWORD_STRENGTH) { refinementContext.addIssue({ @@ -210,56 +148,27 @@ const Wizard: NextPageWithLayout = () => { // default instance size in this case. const instanceSize = canChooseInstanceSize ? watchedInstanceSize ?? sizes[0] : undefined - const { data: membersExceededLimit } = useFreeProjectLimitCheckQuery( + const { data: membersExceededLimit = [] } = useFreeProjectLimitCheckQuery( { slug }, { enabled: isFreePlan } ) - const hasMembersExceedingFreeTierLimit = (membersExceededLimit || []).length > 0 + const hasMembersExceedingFreeTierLimit = membersExceededLimit.length > 0 const freePlanWithExceedingLimits = isFreePlan && hasMembersExceedingFreeTierLimit - const { data: organizations, isSuccess: isOrganizationsSuccess } = useOrganizationsQuery() - const isInvalidSlug = isOrganizationsSuccess && currentOrg === undefined - const orgNotFound = isOrganizationsSuccess && (organizations?.length ?? 0) > 0 && isInvalidSlug - const isEmptyOrganizations = (organizations?.length ?? 0) <= 0 && isOrganizationsSuccess + const { data: organizations = [], isSuccess: isOrganizationsSuccess } = useOrganizationsQuery() + const isEmptyOrganizations = isOrganizationsSuccess && organizations.length <= 0 - const { data: approvedOAuthApps } = useAuthorizedAppsQuery( + const { data: approvedOAuthApps = [] } = useAuthorizedAppsQuery( { slug }, { enabled: !isFreePlan && slug !== '_' } ) - const hasOAuthApps = approvedOAuthApps && approvedOAuthApps.length > 0 - - const isNotOnTeamOrEnterprisePlan = useMemo( - () => !['team', 'enterprise'].includes(currentOrg?.plan.id ?? ''), - [currentOrg] - ) + const hasOAuthApps = approvedOAuthApps.length > 0 - const { data: allOverdueInvoices } = useOverdueInvoicesQuery({ + const { data: allOverdueInvoices = [] } = useOverdueInvoicesQuery({ enabled: isNotOnTeamOrEnterprisePlan, }) - const overdueInvoices = (allOverdueInvoices ?? []).filter( - (x) => x.organization_id === currentOrg?.id - ) - const hasOutstandingInvoices = overdueInvoices.length > 0 && isNotOnTeamOrEnterprisePlan - - const { - mutate: createProject, - isLoading: isCreatingNewProject, - isSuccess: isSuccessNewProject, - } = useProjectCreateMutation({ - onSuccess: (res) => { - track( - 'project_creation_simple_version_submitted', - { - instanceSize: form.getValues('instanceSize'), - }, - { - project: res.ref, - organization: res.organization_slug, - } - ) - router.push(isHomeNew ? `/project/${res.ref}` : `/project/${res.ref}/building`) - }, - }) + const overdueInvoices = allOverdueInvoices.filter((x) => x.organization_id === currentOrg?.id) + const hasOutstandingInvoices = isNotOnTeamOrEnterprisePlan && overdueInvoices.length > 0 const { data: orgProjectsFromApi } = useOrgProjectsInfiniteQuery({ slug: currentOrg?.slug }) const allOrgProjects = useMemo( @@ -268,6 +177,10 @@ const Wizard: NextPageWithLayout = () => { ) const organizationProjects = allProjects?.filter((project) => project.status !== PROJECT_STATUS.INACTIVE) ?? [] + const availableComputeCredits = organizationProjects.length === 0 ? 10 : 0 + const additionalMonthlySpend = isFreePlan + ? 0 + : instanceSizeSpecs[instanceSize as DesiredInstanceSize]!.priceMonthly - availableComputeCredits const { data: _defaultRegion, error: defaultRegionError } = useDefaultRegionQuery( { @@ -326,45 +239,25 @@ const Wizard: NextPageWithLayout = () => { { enabled: currentOrg !== null && !isManagedByVercel } ) - // [kevin] This will eventually all be provided by a new API endpoint to preview and validate project creation, this is just for kaizen now - const monthlyComputeCosts = - // current project costs - organizationProjects.reduce((prev, acc) => { - const primaryDatabase = acc.databases.find((db) => db.identifier === acc.ref) - const cost = !!primaryDatabase ? monthlyInstancePrice(primaryDatabase.infra_compute_size) : 0 - return prev + cost - }, 0) + - // selected compute size - monthlyInstancePrice(instanceSize) - - // compute credits - 10 - - const availableComputeCredits = organizationProjects.length === 0 ? 10 : 0 - - const additionalMonthlySpend = isFreePlan - ? 0 - : instanceSizeSpecs[instanceSize as DesiredInstanceSize]!.priceMonthly - availableComputeCredits - - async function checkPasswordStrength(value: any) { - const { message, warning, strength } = await passwordStrength(value) - - form.setValue('dbPassStrength', strength) - form.trigger('dbPassStrength') - form.trigger('dbPass') - - setPasswordStrengthWarning(warning) - setPasswordStrengthMessage(message) - } - const delayedCheckPasswordStrength = useRef( - debounce((value) => checkPasswordStrength(value), 300) - ).current - - // [Refactor] DB Password could be a common component used in multiple pages with repeated logic - function generatePassword() { - const password = generateStrongPassword() - form.setValue('dbPass', password) - delayedCheckPasswordStrength(password) - } + const { + mutate: createProject, + isLoading: isCreatingNewProject, + isSuccess: isSuccessNewProject, + } = useProjectCreateMutation({ + onSuccess: (res) => { + track( + 'project_creation_simple_version_submitted', + { + instanceSize: form.getValues('instanceSize'), + }, + { + project: res.ref, + organization: res.organization_slug, + } + ) + router.push(isHomeNew ? `/project/${res.ref}` : `/project/${res.ref}/building`) + }, + }) const onSubmitWithComputeCostsConfirmation = async (values: z.infer) => { const launchingLargerInstance = @@ -504,418 +397,44 @@ const Wizard: NextPageWithLayout = () => {
} footer={ -
-
- {!isFreePlan && - !projectCreationDisabled && - canCreateProject && - additionalMonthlySpend > 0 && ( -
- Additional costs -
- ${additionalMonthlySpend}/m - -
-

- Each project includes a dedicated Postgres instance running on its own - server. You are charged for the{' '} - - Compute resource - {' '} - of that server, independent of your database usage. -

- {monthlyComputeCosts > 0 && ( -

- Compute costs are applied on top of your subscription plan costs. -

- )} -
- - - - - Project - Compute Size - Monthly Costs - - - - {organizationProjects.map((project) => { - const primaryDb = project.databases.find( - (db) => db.identifier === project.ref - ) - return ( - - - {project.name} - - - {instanceLabel(primaryDb?.infra_compute_size)} - - - ${monthlyInstancePrice(primaryDb?.infra_compute_size)} - - - ) - })} - - - - - {form.getValues('projectName') - ? form.getValues('projectName') - : 'New project'} - - - NEW - - - - {instanceLabel(instanceSize)} - - - ${monthlyInstancePrice(instanceSize)} - - - -
- - - - - Compute Credits - - -$10 - - - - - - - Total Monthly Compute Costs - {/** - * API currently doesnt output replica information on the projects list endpoint. Until then, we cannot correctly calculate the costs including RRs. - * Will be adjusted in the future [kevin] - */} - {organizationProjects.length > 0 && ( -

- Excluding Read replicas -

- )} -
- - ${monthlyComputeCosts} - -
-
-
-
-
-
- )} -
- -
- - -
-
+ } > <> {projectCreationDisabled ? ( - - - + ) : (
- - {isAdmin && !isInvalidSlug && ( - ( - - {(organizations?.length ?? 0) > 0 && ( - { - field.onChange(slug) - router.push(`/new/${slug}`) - }} - value={field.value} - defaultValue={field.value} - > - - - - - - - - {organizations?.map((x) => ( - - {x.name} - {x.plan.name} - - ))} - - - - )} - - )} - /> - )} - - {isOrganizationsSuccess && !isAdmin && !orgNotFound && ( - - )} - {orgNotFound && } - + {canCreateProject && ( <> - - ( - - - - - - )} - /> - + {cloudProviderEnabled && showNonProdFields && ( - - ( - - { - field.onChange(value) - form.setValue( - 'dbRegion', - value === 'FLY' - ? FLY_REGIONS_DEFAULT.displayName - : AWS_REGIONS_DEFAULT.displayName - ) - }} - defaultValue={field.value} - > - - - - - - - - {Object.values(PROVIDERS) - .filter( - (provider) => - validCloudProviders?.includes(provider.id) ?? true - ) - .map((providerObj) => { - const label = providerObj['name'] - const value = providerObj['id'] - return ( - - {label} - - ) - })} - - - - - )} - /> - - )} - - {canChooseInstanceSize && ( - - ( - -

- The size for your dedicated database. You can change this later. - Learn more about{' '} - - compute add-ons - {' '} - and{' '} - - compute billing - - . -

- - } - > - field.onChange(value)} - > - - - - - - {sizes - .filter((option) => - instanceSizeSpecs[option].cloud_providers.includes( - form.getValues('cloudProvider') as CloudProvider - ) - ) - .map((option) => { - return ( - -
-
- - {instanceSizeSpecs[option].label} - -
-
- - {instanceSizeSpecs[option].ram} RAM /{' '} - {instanceSizeSpecs[option].cpu}{' '} - {getCloudProviderArchitecture( - form.getValues('cloudProvider') as CloudProvider - )}{' '} - CPU - -

- ${instanceSizeSpecs[option].priceHourly}/hour (~$ - {instanceSizeSpecs[option].priceMonthly}/month) -

-
-
-
- ) - })} - -
- Larger instance sizes available after creation -
-
-
-
-
-
- )} - /> -
+ )} - - { - const hasSpecialCharacters = - field.value.length > 0 && !field.value.match(SPECIAL_CHARS_REGEX) + {canChooseInstanceSize && } - return ( - - {hasSpecialCharacters && } - - - } - > - - 0} - type="password" - placeholder="Type in a strong password" - {...field} - autoComplete="off" - onChange={async (event) => { - field.onChange(event) - form.trigger('dbPassStrength') - const value = event.target.value - if (event.target.value === '') { - await form.setValue('dbPassStrength', 0) - await form.trigger('dbPass') - } else { - await delayedCheckPasswordStrength(value) - } - }} - /> - - - ) - }} - /> - + - - ( - - )} - /> - + {showPostgresVersionSelector && ( @@ -935,29 +454,7 @@ const Wizard: NextPageWithLayout = () => { )} - {showNonProdFields && ( - - ( - - - - - - )} - /> - - )} + {showNonProdFields && } {showAdvancedConfig && !!availableOrioleVersion && ( @@ -969,9 +466,7 @@ const Wizard: NextPageWithLayout = () => { {freePlanWithExceedingLimits ? ( isAdmin && slug && ( - - - + ) ) : isManagedByVercel ? ( @@ -1046,20 +541,6 @@ const Wizard: NextPageWithLayout = () => { ) } -/** - * When launching new projects, they only get assigned a compute size once successfully launched, - * this might assume wrong compute size, but only for projects being rapidly launched after one another on non-default compute sizes. - * - * Needs to be in the API in the future [kevin] - */ -const monthlyInstancePrice = (instance: string | undefined): number => { - return instanceSizeSpecs[instance as DesiredInstanceSize]?.priceMonthly || 10 -} - -const instanceLabel = (instance: string | undefined): string => { - return instanceSizeSpecs[instance as DesiredInstanceSize]?.label || 'Micro' -} - const PageLayout = withAuth(({ children }: PropsWithChildren) => { return {children} }) diff --git a/apps/studio/pages/project/[ref]/auth/templates/[templateId].tsx b/apps/studio/pages/project/[ref]/auth/templates/[templateId].tsx new file mode 100644 index 0000000000000..f3097485c6b12 --- /dev/null +++ b/apps/studio/pages/project/[ref]/auth/templates/[templateId].tsx @@ -0,0 +1,117 @@ +import { PermissionAction } from '@supabase/shared-types/out/constants' + +import { useIsSecurityNotificationsEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext' +import { TEMPLATES_SCHEMAS } from 'components/interfaces/Auth/AuthTemplatesValidation' +import { slugifyTitle } from 'components/interfaces/Auth/EmailTemplates/EmailTemplates.utils' +import TemplateEditor from 'components/interfaces/Auth/EmailTemplates/TemplateEditor' +import AuthLayout from 'components/layouts/AuthLayout/AuthLayout' +import DefaultLayout from 'components/layouts/DefaultLayout' +import { PageLayout } from 'components/layouts/PageLayout/PageLayout' +import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold' +import { DocsButton } from 'components/ui/DocsButton' +import NoPermission from 'components/ui/NoPermission' +import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions' +import { DOCS_URL } from 'lib/constants' +import Link from 'next/link' +import { useRouter } from 'next/router' +import { useEffect } from 'react' +import type { NextPageWithLayout } from 'types' +import { Button, Card } from 'ui' +import { Admonition, GenericSkeletonLoader } from 'ui-patterns' + +const TemplatePage: NextPageWithLayout = () => { + return +} + +const RedirectToTemplates = () => { + const router = useRouter() + const { templateId, ref } = router.query + const isSecurityNotificationsEnabled = useIsSecurityNotificationsEnabled() + + const { can: canReadAuthSettings, isSuccess: isPermissionsLoaded } = useAsyncCheckPermissions( + PermissionAction.READ, + 'custom_config_gotrue' + ) + + useEffect(() => { + if (isPermissionsLoaded && !isSecurityNotificationsEnabled) { + router.replace(`/project/${ref}/auth/templates/`) + } + }, [isPermissionsLoaded, isSecurityNotificationsEnabled, ref, router]) + + if (isPermissionsLoaded && !canReadAuthSettings) { + return + } + + if (!isSecurityNotificationsEnabled) { + return null + } + + // Find template whose slug matches the URL slug + const template = + templateId && typeof templateId === 'string' + ? TEMPLATES_SCHEMAS.find((template) => slugifyTitle(template.title) === templateId) + : null + + // Show error if templateId is invalid or template is not found + if (!template || !templateId || typeof templateId !== 'string') { + return ( +
+ + + +
+ ) + } + + // Convert templateId slug to one lowercase word to match docs anchor tag + const templateIdForDocs = templateId.replace(/-/g, '').toLowerCase() + + return ( + , + ]} + > + + {!isPermissionsLoaded ? ( + + + + ) : ( + + + + + + )} + + + ) +} + +TemplatePage.getLayout = (page) => ( + + {page} + +) + +export default TemplatePage diff --git a/apps/studio/pages/project/[ref]/auth/templates.tsx b/apps/studio/pages/project/[ref]/auth/templates/index.tsx similarity index 97% rename from apps/studio/pages/project/[ref]/auth/templates.tsx rename to apps/studio/pages/project/[ref]/auth/templates/index.tsx index cc1ccbaa0fed5..dbd048e4938a6 100644 --- a/apps/studio/pages/project/[ref]/auth/templates.tsx +++ b/apps/studio/pages/project/[ref]/auth/templates/index.tsx @@ -20,7 +20,7 @@ const TemplatesPage: NextPageWithLayout = () => { } return ( - + {!isPermissionsLoaded ? ( diff --git a/apps/studio/types/form.ts b/apps/studio/types/form.ts index 061b8a7105c34..8a4bf1380d6a1 100644 --- a/apps/studio/types/form.ts +++ b/apps/studio/types/form.ts @@ -9,6 +9,7 @@ export interface FormSchema { id?: string type: 'object' title: string + purpose?: string properties: { [x: string]: { title: string diff --git a/packages/ui-patterns/package.json b/packages/ui-patterns/package.json index 5df8c48b9e3fa..3114adf3e37f1 100644 --- a/packages/ui-patterns/package.json +++ b/packages/ui-patterns/package.json @@ -486,6 +486,7 @@ "dependencies": { "@hookform/resolvers": "^3.1.1", "@monaco-editor/react": "^4.6.0", + "@radix-ui/react-visually-hidden": "^1.1.3", "@supabase/sql-to-rest": "^0.1.6", "@supabase/supabase-js": "catalog:", "@vitest/coverage-v8": "^3.0.9", diff --git a/packages/ui-patterns/src/CommandMenu/api/CommandInput.tsx b/packages/ui-patterns/src/CommandMenu/api/CommandInput.tsx index afa27b8361c5a..37b38e814500d 100644 --- a/packages/ui-patterns/src/CommandMenu/api/CommandInput.tsx +++ b/packages/ui-patterns/src/CommandMenu/api/CommandInput.tsx @@ -124,7 +124,7 @@ const CommandInput = forwardRef< onCompositionStart={() => setImeComposing(true)} onCompositionEnd={() => setImeComposing(false)} className={cn( - 'flex h-11 w-full rounded-md bg-transparent px-4 py-7 outline-none', + 'flex h-11 w-full rounded-md bg-transparent px-2 py-7 outline-none', 'focus:shadow-none focus:ring-transparent', 'text-base text-foreground-light placeholder:text-foreground-muted disabled:cursor-not-allowed disabled:opacity-50 border-0', className diff --git a/packages/ui-patterns/src/CommandMenu/api/CommandMenu.tsx b/packages/ui-patterns/src/CommandMenu/api/CommandMenu.tsx index 1c1238310ef2a..ed3f484843919 100644 --- a/packages/ui-patterns/src/CommandMenu/api/CommandMenu.tsx +++ b/packages/ui-patterns/src/CommandMenu/api/CommandMenu.tsx @@ -1,5 +1,5 @@ 'use client' - +import { VisuallyHidden } from '@radix-ui/react-visually-hidden' import { AlertTriangle, ArrowLeft, Command, Search } from 'lucide-react' import type { HTMLAttributes, MouseEvent, PropsWithChildren, ReactElement, ReactNode } from 'react' import { Children, cloneElement, forwardRef, isValidElement, useEffect, useMemo } from 'react' @@ -7,14 +7,22 @@ import { ErrorBoundary } from 'react-error-boundary' import { useBreakpoint } from 'common' import useDragToClose from 'common/hooks/useDragToClose' -import { Button, Command_Shadcn_, Dialog, DialogContent, cn } from 'ui' +import { + Button, + Command_Shadcn_, + Dialog, + DialogContent, + DialogDescription, + DialogTitle, + cn, +} from 'ui' import { useCurrentPage, usePageComponent, usePopPage } from './hooks/pagesHooks' import { useQuery, useSetQuery } from './hooks/queryHooks' import { useCommandMenuTelemetryContext } from './hooks/useCommandMenuTelemetryContext' import { - useCommandMenuSize, useCommandMenuOpen, + useCommandMenuSize, useSetCommandMenuOpen, useSetupCommandMenuTouchEvents, } from './hooks/viewHooks' @@ -252,6 +260,10 @@ function CommandMenu({ children, trigger }: CommandMenuProps) { className: cn('overflow-hidden flex data-closed:delay-100'), }} > + + Command menu + Type a command or search + {children} diff --git a/packages/ui-patterns/src/CommandMenu/prepackaged/Changelog.tsx b/packages/ui-patterns/src/CommandMenu/prepackaged/Changelog.tsx index 2827eccd9f306..5ba4f161d9e5d 100644 --- a/packages/ui-patterns/src/CommandMenu/prepackaged/Changelog.tsx +++ b/packages/ui-patterns/src/CommandMenu/prepackaged/Changelog.tsx @@ -9,7 +9,7 @@ const useChangelogCommand = ({ enabled = true }: { enabled?: boolean } = {}) => [ { id: 'changelog', - name: 'Changelog', + name: 'View changelog', route: BASE_PATH ? 'https://supabase.com/changelog' : '/changelog', icon: () => , }, diff --git a/packages/ui-patterns/src/CommandMenu/prepackaged/Support.tsx b/packages/ui-patterns/src/CommandMenu/prepackaged/Support.tsx index b7d9bf3530c07..9debed79e2f80 100644 --- a/packages/ui-patterns/src/CommandMenu/prepackaged/Support.tsx +++ b/packages/ui-patterns/src/CommandMenu/prepackaged/Support.tsx @@ -1,4 +1,4 @@ -import { LifeBuoy } from 'lucide-react' +import { LifeBuoy, Activity } from 'lucide-react' import { useMemo } from 'react' import { useRegisterCommands, useSetCommandMenuOpen, type ICommand } from '..' @@ -10,25 +10,25 @@ const useSupportCommands = ({ enabled = true }: { enabled?: boolean } = {}) => { const commands = useMemo( () => [ - { - id: 'support', - name: 'Go to Support', - value: 'Support: Go to Support', - href: '/support', - icon: () => , - }, { id: 'system-status', - name: 'Go to System Status', - value: 'Support: Go to System Status', + name: 'View system status', + value: 'Support: View system status', href: 'https://status.supabase.com', + icon: () => , + }, + { + id: 'discord-community', + name: 'Ask Discord community', + value: 'Support: Ask Discord community', + href: 'https://discord.supabase.com', icon: () => , }, { - id: 'github-discussions', - name: 'Go to GitHub Discussions', - value: 'Support: Go to GitHub Discussions', - href: 'https://github.com/orgs/supabase/discussions', + id: 'support-team', + name: 'Contact support', + value: 'Support: Contact support', + href: '/support', icon: () => , }, ].map((command) => ({ diff --git a/packages/ui/src/components/shadcn/ui/command.tsx b/packages/ui/src/components/shadcn/ui/command.tsx index 84cb0361bab9a..bcba65695eef2 100644 --- a/packages/ui/src/components/shadcn/ui/command.tsx +++ b/packages/ui/src/components/shadcn/ui/command.tsx @@ -57,12 +57,12 @@ const CommandInput = React.forwardRef< }, ref ) => ( -
+
{showSearchIcon && }