Files
supabase/apps/studio/data/network-restrictions/network-restrictions-query.ts
T
Joshen LimandIvan Vasilov 163263c3c5 First round of wrapping RQ errors with handleError (#26384)
* First round of wrapping RQ errors with handleError

* Remove the throw before the handleError usage.

* Make the handling of an API error more versatile. Add logging in Sentry if the error is of unknown type.

* Remove throwing of the handleError function.

* Add return type to the handleError function to be never so that we're sure it always throws.

---------

Co-authored-by: Ivan Vasilov <vasilov.ivan@gmail.com>
2024-05-17 16:30:55 +08:00

63 lines
1.9 KiB
TypeScript

import { useQuery, UseQueryOptions } from '@tanstack/react-query'
import { get, handleError } from 'data/fetchers'
import { networkRestrictionKeys } from './keys'
export type NetworkRestrictionsVariables = { projectRef?: string }
export type NetworkRestrictionsResponse = {
entitlement: 'disallowed' | 'allowed'
status: '' | 'stored' | 'applied'
config: { dbAllowedCidrs: string[] }
old_config?: { dbAllowedCidrs: string[] }
error?: any
}
export async function getNetworkRestrictions(
{ projectRef }: NetworkRestrictionsVariables,
signal?: AbortSignal
) {
if (!projectRef) throw new Error('projectRef is required')
const { data, error } = await get('/v1/projects/{ref}/network-restrictions', {
params: { path: { ref: projectRef } },
signal,
})
// Not allowed error is a valid response to denote if a project
// has access to the network restrictions UI, so we'll handle it here
if (error) {
const isNotAllowedError =
(error as any)?.code === 400 &&
(error as any)?.message?.includes('not allowed to set up network restrictions')
if (isNotAllowedError) {
return {
entitlement: 'disallowed',
config: { dbAllowedCidrs: [] },
status: '',
} as NetworkRestrictionsResponse
} else {
handleError(error)
}
}
return data
}
export type NetworkRestrictionsData = Awaited<ReturnType<typeof getNetworkRestrictions>>
export type NetworkRestrictionsError = unknown
export const useNetworkRestrictionsQuery = <TData = NetworkRestrictionsData>(
{ projectRef }: NetworkRestrictionsVariables,
{
enabled = true,
...options
}: UseQueryOptions<NetworkRestrictionsData, NetworkRestrictionsError, TData> = {}
) =>
useQuery<NetworkRestrictionsData, NetworkRestrictionsError, TData>(
networkRestrictionKeys.list(projectRef),
({ signal }) => getNetworkRestrictions({ projectRef }, signal),
{ enabled: enabled && typeof projectRef !== 'undefined', ...options }
)