Refactor error handling for projects mutation

This commit is contained in:
Joshen Lim committed 2023-07-11 21:46:47 +08:00
1 parent cc320af73d
commit 309e63b137
4 files changed
+39 -38

No files matched your search

@@ -77,7 +77,6 @@ const TransferProjectButton: FC<{}> = () => {
await transferProject({ projectRef, targetOrganizationSlug: selectedOrg })
ui.setNotification({
category: 'success',
duration: 5000,
message: `Successfully transferred project ${project?.name}.`,
})
@@ -1,7 +1,9 @@
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'react-hot-toast'
import { post } from 'lib/common/fetch'
import { API_URL, PRICING_TIER_PRODUCT_IDS, PROVIDERS } from 'lib/constants'
import { ProjectBase } from 'types'
import { ProjectBase, ResponseError } from 'types'
import { projectKeys } from './keys'
export type ProjectCreateVariables = {
@@ -32,10 +34,7 @@ export async function createProject({
// auth_site_url: _store.selectedVercelProjectUrl,
vercel_configuration_id: configurationId,
})
if (response.error) {
throw response.error
}
if (response.error) throw response.error
return response as ProjectBase
}
@@ -43,20 +42,28 @@ type ProjectCreateData = Awaited<ReturnType<typeof createProject>>
export const useProjectCreateMutation = ({
onSuccess,
onError,
...options
}: Omit<
UseMutationOptions<ProjectCreateData, unknown, ProjectCreateVariables>,
UseMutationOptions<ProjectCreateData, ResponseError, ProjectCreateVariables>,
'mutationFn'
> = {}) => {
const queryClient = useQueryClient()
return useMutation<ProjectCreateData, unknown, ProjectCreateVariables>(
return useMutation<ProjectCreateData, ResponseError, ProjectCreateVariables>(
(vars) => createProject(vars),
{
async onSuccess(data, variables, context) {
await queryClient.invalidateQueries(projectKeys.list()),
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {
if (onError === undefined) {
toast.error(`Failed to create project: ${data.message}`)
} else {
onError(data, variables, context)
}
},
...options,
}
)
@@ -1,4 +1,6 @@
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'react-hot-toast'
import { post } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
import { projectKeys } from './keys'
@@ -33,6 +35,7 @@ type ProjectTransferData = Awaited<ReturnType<typeof transferProject>>
export const useProjectTransferMutation = ({
onSuccess,
onError,
...options
}: Omit<
UseMutationOptions<ProjectTransferData, ProjectTransferError, ProjectTransferVariables>,
@@ -54,6 +57,13 @@ export const useProjectTransferMutation = ({
])
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,
}
)
@@ -1,3 +1,4 @@
import generator from 'generate-password'
import { debounce } from 'lodash'
import { useRouter } from 'next/router'
import { ChangeEvent, useRef, useState } from 'react'
@@ -14,12 +15,11 @@ import { useVercelProjectsQuery } from 'data/integrations/integrations-vercel-pr
import { Integration } from 'data/integrations/integrations.types'
import { useOrganizationsQuery } from 'data/organizations/organizations-query'
import { useProjectCreateMutation } from 'data/projects/project-create-mutation'
import generator from 'generate-password'
import { useSelectedOrganization, useStore } from 'hooks'
import { AWS_REGIONS, DEFAULT_MINIMUM_PASSWORD_STRENGTH, PROVIDERS } from 'lib/constants'
import { passwordStrength } from 'lib/helpers'
import { getInitialMigrationSQLFromGitHubRepo } from 'lib/integration-utils'
import { NextPageWithLayout, ProjectBase } from 'types'
import { NextPageWithLayout } from 'types'
import { Alert, Button, Checkbox, IconBook, IconLifeBuoy, Input, Listbox, LoadingLine } from 'ui'
const VercelIntegration: NextPageWithLayout = () => {
@@ -79,7 +79,7 @@ const CreateProject = ({
const [passwordStrengthScore, setPasswordStrengthScore] = useState(-1)
const [shouldRunMigrations, setShouldRunMigrations] = useState(true)
const [dbRegion, setDbRegion] = useState(PROVIDERS.AWS.default_region)
// const [loading, setLoading] = useState(false)
const delayedCheckPasswordStrength = useRef(
debounce((value: string) => checkPasswordStrength(value), 300)
).current
@@ -96,7 +96,6 @@ const CreateProject = ({
useIntegrationConnectionsCreateMutation({})
const { data: organizationData, isLoading: isLoadingOrganizationsQuery } = useOrganizationsQuery()
const organization = organizationData?.find((x) => x.slug === slug)
/**
@@ -183,9 +182,7 @@ const CreateProject = ({
setLoading(true)
try {
if (!organization) {
throw new Error('No organization set')
}
if (!organization) throw new Error('No organization set')
let dbSql: string | undefined
if (shouldRunMigrations) {
@@ -203,29 +200,17 @@ const CreateProject = ({
})
}
let project: ProjectBase
try {
project = await createProject({
organizationId: organization.id,
name: projectName,
dbPass,
dbRegion,
dbSql,
configurationId,
})
setNewProjectRef(project.ref)
} catch (error: any) {
setLoading(false)
ui.setNotification({
category: 'error',
message: `Failed to create project: ${error.message}`,
})
return
}
} catch (error) {
console.error('Error', error)
const project = await createProject({
organizationId: organization.id,
name: projectName,
dbPass,
dbRegion,
dbSql,
configurationId,
})
setNewProjectRef(project.ref)
} catch (error: any) {
ui.setNotification({ error, category: 'error', message: error.message })
setLoading(false)
}
}