The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Init network restrictions ui set up
Joshen Lim37c90cbf20ff
diff --git a/studio/components/interfaces/Settings/General/NetworkRestrictions/NetworkRestrictions.tsx b/studio/components/interfaces/Settings/General/NetworkRestrictions/NetworkRestrictions.tsxnew file mode 100644index 00000000000..683e20114be--- /dev/null+++ b/studio/components/interfaces/Settings/General/NetworkRestrictions/NetworkRestrictions.tsx@@ -0,0 +1,22 @@+import { FormHeader } from 'components/ui/Forms'++import { useNetworkRestrictionsQuery } from 'data/network-restrictions/network-restrictions-query'+import { useParams } from 'hooks'++const NetworkRestrictions = ({}) => {+ const { ref } = useParams()+ const { data, isLoading, isError, isSuccess } = useNetworkRestrictionsQuery({ projectRef: ref })++ console.log(data)++ return (+ <section>+ <FormHeader+ title="Network Restrictions"+ description="Control access to your database via IP addresses"+ />+ </section>+ )+}++export default NetworkRestrictionsdiff --git a/studio/components/interfaces/Settings/General/index.ts b/studio/components/interfaces/Settings/General/index.tsindex 108fd79d1a7..59a3ebc7e63 100644--- a/studio/components/interfaces/Settings/General/index.ts+++ b/studio/components/interfaces/Settings/General/index.ts@@ -1,6 +1,15 @@import General from './General'import Infrastructure from './Infrastructure/Infrastructure'+import CustomDomainConfig from './CustomDomainConfig/CustomDomainConfig'+import NetworkRestrictions from './NetworkRestrictions/NetworkRestrictions'import DeleteProjectPanel from './DeleteProjectPanel/DeleteProjectPanel'import DeleteProjectButton from './DeleteProjectPanel/DeleteProjectButton'-export { General, Infrastructure, DeleteProjectPanel, DeleteProjectButton }+export {+ General,+ Infrastructure,+ CustomDomainConfig,+ NetworkRestrictions,+ DeleteProjectPanel,+ DeleteProjectButton,+}diff --git a/studio/data/network-restrictions/README.md b/studio/data/network-restrictions/README.mdnew file mode 100644index 00000000000..05a0cabfb4f--- /dev/null+++ b/studio/data/network-restrictions/README.md@@ -0,0 +1,49 @@+# Templates for Tanstack Query queries & mutations++## Usage++1. Duplicate the files in the \_\_templates directory you need depending on your use case.+2. Rename the files to match your resource name.+3. Update the `resource` variables to match your resource name. Usually find and replace works great here if you use case sensitive search (`resource` then `Resource`)+4. Implement your `queryFn` function.++Referencing the other files in the `data` directory is a good way to see how to use the library.++### SQL queries and mutations++The dashboard often needs to query the users database directly. There are already some reusable hooks for this in `data/sql`. Reference the `data/fdw` directory for an example of how to use them.++Note that the query key of the `useExecuteSqlQuery` hook will be automatically filled with an md5 hash of the SQL query, unless you provide a name for the query.++## Files++### `resources-query.ts`++For queries that return a list of results.++> :warning: Should only be used for simple lists, as it does not include any pagination. `useInfiniteQuery` should be used instead.++### `resource-query.ts`++For getting a single item based on parameter(s). `id` is used in this example but can be updated to whatever is needed.++### `resource-update-mutation.ts`++For updating a resource. This can easily be adapted to work for create, delete, or any verb that is needed. You may need to modify the `invalidateQueries` section depending on your use case. For example removing:++```ts+queryClient.invalidateQueries(resourceKeys.resource(projectRef, id))+```++if you are creating a new resource.++### `keys.ts`++Standardized keys for use with `useQuery` and `invalidateQueries`. This is not required but is a good way to keep things consistent.++## Learning Resources++- [Tanstack Query Docs](https://tanstack.com/query/v4/docs/react/overview)+- [TkDodo's Blog Posts](https://tanstack.com/query/v4/docs/react/community/tkdodos-blog)++The blog posts in particular are very helpful for learning best practices and how to use the library effectively.diff --git a/studio/data/network-restrictions/keys.ts b/studio/data/network-restrictions/keys.tsnew file mode 100644index 00000000000..264e0497d4c--- /dev/null+++ b/studio/data/network-restrictions/keys.ts@@ -0,0 +1,4 @@+export const networkRestrictionKeys = {+ list: (projectRef: string | undefined) =>+ ['projects', projectRef, 'network-restrictions'] as const,+}diff --git a/studio/data/network-restrictions/network-restrictions-query.ts b/studio/data/network-restrictions/network-restrictions-query.tsnew file mode 100644index 00000000000..0cfc7ec1620--- /dev/null+++ b/studio/data/network-restrictions/network-restrictions-query.ts@@ -0,0 +1,69 @@+import { useCallback } from 'react'+import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'++import { networkRestrictionKeys } from './keys'+import { get } from 'lib/common/fetch'+import { API_ADMIN_URL } from 'lib/constants'++export type NetworkRestrictionsVariables = { projectRef?: string }++export type NetworkRestrictionsResponse = {+ entitlement: 'disallowed' | 'allowed'+ status: 'stored' | 'applied'+ config: any+}++export async function getNetworkRestrictions(+ { projectRef }: NetworkRestrictionsVariables,+ signal?: AbortSignal+) {+ if (!projectRef) throw new Error('projectRef is required')++ const response = await get(`${API_ADMIN_URL}/projects/${projectRef}/network-restrictions`, {+ 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 (response.error) {+ const isNotAllowedError =+ (response.error as any)?.code === 400 &&+ (response.error as any)?.message?.includes('to be updated')++ if (isNowAllowedError) {+ return {}+ } else {+ throw response.error+ }+ }++ return response as NetworkRestrictionsResponse[]+}++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 }+ )++export const useNetworkRestrictionsPrefetch = ({ projectRef }: NetworkRestrictionsVariables) => {+ const client = useQueryClient()++ return useCallback(() => {+ if (projectRef) {+ client.prefetchQuery(networkRestrictionKeys.list(projectRef), ({ signal }) =>+ getNetworkRestrictions({ projectRef }, signal)+ )+ }+ }, [projectRef])+}diff --git a/studio/data/network-restrictions/network-retrictions-apply-mutation.ts b/studio/data/network-restrictions/network-retrictions-apply-mutation.tsnew file mode 100644index 00000000000..1adc146c9b3--- /dev/null+++ b/studio/data/network-restrictions/network-retrictions-apply-mutation.ts@@ -0,0 +1,51 @@+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { patch } from 'lib/common/fetch'+import { API_ADMIN_URL } from 'lib/constants'+import { networkRestrictionKeys } from './keys'++export type NetworkRestrictionsApplyVariables = {+ projectRef: string+ id: string+ updatedParam: string+}++export async function applyNetworkRestrictions({+ projectRef,+ updatedParam,+}: NetworkRestrictionsApplyVariables) {+ if (!projectRef) throw new Error('projectRef is required')++ const response = await patch(+ `${API_ADMIN_URL}/projects/${projectRef}/network-restrictions/apply`,+ { updated_param: updatedParam }+ )+ if (response.error) {+ throw response.error+ }++ return response+}++type NetworkRestrictionsApplyData = Awaited<ReturnType<typeof applyNetworkRestrictions>>++export const useNetworkRestrictionsApplyMutation = ({+ onSuccess,+ ...options+}: Omit<+ UseMutationOptions<NetworkRestrictionsApplyData, unknown, NetworkRestrictionsApplyVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<NetworkRestrictionsApplyData, unknown, NetworkRestrictionsApplyVariables>(+ (vars) => applyNetworkRestrictions(vars),+ {+ async onSuccess(data, variables, context) {+ const { projectRef } = variables+ await queryClient.invalidateQueries(networkRestrictionKeys.list(projectRef))+ await onSuccess?.(data, variables, context)+ },+ ...options,+ }+ )+}diff --git a/studio/pages/project/[ref]/settings/general.tsx b/studio/pages/project/[ref]/settings/general.tsxindex 118d21cb6fe..3b722c4c841 100644--- a/studio/pages/project/[ref]/settings/general.tsx+++ b/studio/pages/project/[ref]/settings/general.tsx@@ -1,8 +1,13 @@import { observer } from 'mobx-react-lite'import { NextPageWithLayout } from 'types'import { SettingsLayout } from 'components/layouts'-import { General, Infrastructure, DeleteProjectPanel } from 'components/interfaces/Settings/General'-import CustomDomainConfig from 'components/interfaces/Settings/General/CustomDomainConfig/CustomDomainConfig'+import {+ General,+ Infrastructure,+ CustomDomainConfig,+ NetworkRestrictions,+ DeleteProjectPanel,+} from 'components/interfaces/Settings/General'const ProjectSettings: NextPageWithLayout = () => {return (@@ -10,6 +15,7 @@ const ProjectSettings: NextPageWithLayout = () => {<General /><Infrastructure /><CustomDomainConfig />+ <NetworkRestrictions /><DeleteProjectPanel /></div>)