Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Refactor API settings component to use new form component

Joshen Lim783bf3c6885d
diff --git a/studio/components/interfaces/Settings/API/PostgrestConfig.tsx b/studio/components/interfaces/Settings/API/PostgrestConfig.tsx
index 24b02df89df..09902c3e2f4 100644
--- a/studio/components/interfaces/Settings/API/PostgrestConfig.tsx
+++ b/studio/components/interfaces/Settings/API/PostgrestConfig.tsx
@@ -1,19 +1,23 @@
-import { useContext, useState, FC } from 'react'
+import { useContext, FC, useEffect } from 'react'
import { indexOf } from 'lodash'
import { useRouter } from 'next/router'
-import { AutoField } from 'uniforms-bootstrap4'
import { observer } from 'mobx-react-lite'
-import { IconAlertCircle } from '@supabase/ui'
+import { Input, Form, IconAlertCircle, InputNumber } from '@supabase/ui'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
import { checkPermissions, useStore, useProjectPostgrestConfig } from 'hooks'
import { API_URL } from 'lib/constants'
import { patch } from 'lib/common/fetch'
-import SchemaFormPanel from 'components/to-be-cleaned/forms/SchemaFormPanel'
import MultiSelect from 'components/ui/MultiSelect'
import { PageContext } from 'pages/project/[ref]/settings/api'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-// [Joshen TODO] Refactor to use supabase form component and FormPanel component
+import {
+ FormActions,
+ FormPanel,
+ FormSection,
+ FormSectionContent,
+ FormSectionLabel,
+} from 'components/ui/Forms'
interface Props {}
@@ -25,13 +29,14 @@ const PostgrestConfig: FC<Props> = ({}) => {
const router = useRouter()
const { ref } = router.query
- const { config, isError } = useProjectPostgrestConfig(ref as string | undefined)
+ const formId = 'project-postgres-config'
+ const { config, isError, isLoading } = useProjectPostgrestConfig(ref as string | undefined)
- const [updates, setUpdates] = useState({
- db_schema: config?.db_schema,
- max_rows: config?.max_rows,
- db_extra_search_path: config?.db_extra_search_path ?? '',
- })
+ const initialValues = {
+ db_schema: '',
+ max_rows: '',
+ db_extra_search_path: '',
+ }
const canUpdatePostgrestConfig = checkPermissions(
PermissionAction.UPDATE,
@@ -55,11 +60,8 @@ const PostgrestConfig: FC<Props> = ({}) => {
}
}
- // manually filter out following schema
- const hiddenSchema = ['auth', 'pgbouncer', 'hooks', 'extensions']
- // following schema is permament
const permanentSchema = ['public', 'storage']
- // construct list of schema for input controller
+ const hiddenSchema = ['auth', 'pgbouncer', 'hooks', 'extensions']
const schema =
meta.schemas
.list(
@@ -79,96 +81,117 @@ const PostgrestConfig: FC<Props> = ({}) => {
}) ?? []
return (
- <>
- <SchemaFormPanel
- title="Settings"
- schema={{
- properties: {
- db_schema: {
- title: 'Schema',
- type: 'string',
- help: 'The schema to expose in your API. Tables, views and stored procedures in this schema will get API endpoints. Multiple schemas must be comma-separated.',
- },
- max_rows: {
- title: 'Max Rows',
- type: 'integer',
- help: 'The maximum number of rows returns from a view, table, or stored procedure. Limits payload size for accidental or malicious requests.',
- },
- db_extra_search_path: {
- title: 'Extra search path',
- type: 'string',
- help: 'Extra schemas to add to the search_path of every request. Multiple schemas must be comma-separated.',
- },
- },
- required: ['max_rows'],
- type: 'object',
- }}
- model={updates}
- message={
- !canUpdatePostgrestConfig
- ? "You need additional permissions to update your project's API settings"
- : undefined
- }
- onSubmit={(model: any) => updateConfig(model)}
- onReset={() => setUpdates(config)}
- >
- {isError ? (
- <div className="py-8 flex items-center justify-center space-x-2">
- <IconAlertCircle size={16} strokeWidth={1.5} />
- <p className="text-sm text-scale-1100">Failed to retrieve API settings</p>
- </div>
- ) : (
- <div className="space-y-6 py-4">
- {schema.length >= 1 && (
- <MultiSelect
- disabled={!canUpdatePostgrestConfig}
- options={schema}
- // value must be passed as array of strings
- value={updates.db_schema.replace(/ /g, '').split(',')}
- // onChange returns array of strings
- onChange={(event) => {
- let payload = updates
- payload.db_schema = event.join(', ') // permanentSchema.concat(event).join(', ')
- setUpdates({ ...payload })
- updateConfig({ ...payload })
- }}
- label={'Schema'}
- descriptionText={
- <>
- The schema to expose in your API. Tables, views and stored procedures in this
- schema will get API endpoints.<code>public</code> and <code>storage</code> are
- protected by default.
- </>
- }
- emptyMessage={
- <>
- <IconAlertCircle strokeWidth={2} />
- <div className="mt-2 flex flex-col text-center">
- <p className="text-sm align-center">No schema available to choose</p>
- <p className="text-xs opacity-50">New schemas you create will appear here</p>
- </div>
- </>
- }
- />
- )}
- <AutoField
- disabled={!canUpdatePostgrestConfig}
- name="db_extra_search_path"
- showInlineError
- errorMessage="Must be a string."
- className={`${!canUpdatePostgrestConfig ? 'opacity-50' : ''}`}
- />
- <AutoField
- disabled={!canUpdatePostgrestConfig}
- name="max_rows"
- showInlineError
- errorMessage="Must be a number."
- className={`${!canUpdatePostgrestConfig ? 'opacity-50' : ''}`}
- />
- </div>
- )}
- </SchemaFormPanel>
- </>
+ <Form id={formId} initialValues={initialValues} validate={() => {}} onSubmit={updateConfig}>
+ {({ isSubmitting, handleReset, resetForm, values, initialValues }: any) => {
+ const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)
+
+ useEffect(() => {
+ if (!isLoading && config) {
+ const values = {
+ db_schema: config.db_schema,
+ max_rows: config.max_rows,
+ db_extra_search_path: config.db_extra_search_path ?? '',
+ }
+ resetForm({ values, initialValues: values })
+ }
+ }, [isLoading])
+
+ return (
+ <>
+ <FormPanel
+ disabled={true}
+ header={<p>API settings</p>}
+ footer={
+ <div className="flex py-4 px-8">
+ <FormActions
+ form={formId}
+ isSubmitting={isSubmitting}
+ hasChanges={hasChanges}
+ handleReset={handleReset}
+ disabled={!canUpdatePostgrestConfig}
+ helper={
+ !canUpdatePostgrestConfig
+ ? "You need additional permissions to update your project's API settings"
+ : undefined
+ }
+ />
+ </div>
+ }
+ >
+ {isError ? (
+ <div className="py-8 flex items-center justify-center space-x-2">
+ <IconAlertCircle size={16} strokeWidth={1.5} />
+ <p className="text-sm text-scale-1100">Failed to retrieve API settings</p>
+ </div>
+ ) : (
+ <>
+ <FormSection header={<FormSectionLabel>Exposed schemas</FormSectionLabel>}>
+ <FormSectionContent loading={false}>
+ {schema.length >= 1 && (
+ <MultiSelect
+ disabled={!canUpdatePostgrestConfig}
+ options={schema}
+ descriptionText={
+ <>
+ The schemas to expose in your API. Tables, views and stored procedures
+ in these schemas will get API endpoints.
+ <code className="text-xs">public</code> and{' '}
+ <code className="text-xs">storage</code> are protected by default.
+ </>
+ }
+ emptyMessage={
+ <>
+ <IconAlertCircle strokeWidth={2} />
+ <div className="mt-2 flex flex-col text-center">
+ <p className="text-sm align-center">
+ No schema available to choose
+ </p>
+ <p className="text-xs opacity-50">
+ New schemas you create will appear here
+ </p>
+ </div>
+ </>
+ }
+ // value must be passed as array of strings
+ value={(values?.db_schema ?? '').replace(/ /g, '').split(',')}
+ // onChange returns array of strings
+ onChange={(event) => {
+ let updatedValues: any = values
+ updatedValues.db_schema = event.join(', ')
+ resetForm({ values: updatedValues, initialValues: updatedValues })
+ updateConfig({ ...updatedValues })
+ }}
+ />
+ )}
+ </FormSectionContent>
+ </FormSection>
+ <FormSection header={<FormSectionLabel>Extra search path</FormSectionLabel>}>
+ <FormSectionContent loading={false}>
+ <Input
+ id="db_extra_search_path"
+ size="small"
+ disabled={!canUpdatePostgrestConfig}
+ descriptionText="Extra schemas to add to the search path of every request. Multiple schemas must be comma-separated."
+ />
+ </FormSectionContent>
+ </FormSection>
+ <FormSection header={<FormSectionLabel>Max rows</FormSectionLabel>}>
+ <FormSectionContent loading={false}>
+ <InputNumber
+ id="max_rows"
+ size="small"
+ disabled={!canUpdatePostgrestConfig}
+ descriptionText="The maximum number of rows returned from a view, table, or stored procedure. Limits payload size for accidental or malicious requests."
+ />
+ </FormSectionContent>
+ </FormSection>
+ </>
+ )}
+ </FormPanel>
+ </>
+ )
+ }}
+ </Form>
)
}
diff --git a/studio/components/interfaces/Settings/API/ServiceList.tsx b/studio/components/interfaces/Settings/API/ServiceList.tsx
index 76e3ef87b63..8ef56f1d80a 100644
--- a/studio/components/interfaces/Settings/API/ServiceList.tsx
+++ b/studio/components/interfaces/Settings/API/ServiceList.tsx
@@ -64,7 +64,7 @@ const ServiceList: FC<Props> = ({ projectRef }) => {
return (
<>
- <div className="max-w-4xl p-4">
+ <div className="">
<section>
<Panel title={<h5 className="mb-0">Project URL</h5>}>
<Panel.Content>
diff --git a/studio/components/ui/Forms/FormPanel.tsx b/studio/components/ui/Forms/FormPanel.tsx
index 870676b1738..49c49375e0c 100644
--- a/studio/components/ui/Forms/FormPanel.tsx
+++ b/studio/components/ui/Forms/FormPanel.tsx
@@ -17,11 +17,7 @@ const FormPanel = ({ children, header, footer }: Props) => (
overflow-hidden
rounded-md border shadow"
>
- {header && (
- <div className="bg-scale-100 dark:bg-scale-200 border-scale-400 border-b px-8 py-4">
- {header}
- </div>
- )}
+ {header && <div className=" border-scale-400 border-b px-8 py-4">{header}</div>}
<div className="divide-scale-400 flex flex-col gap-0 divide-y">{children}</div>
{footer && (
<>
diff --git a/studio/components/ui/MultiSelect/index.tsx b/studio/components/ui/MultiSelect/index.tsx
index 9294ee716dc..a3a85005d46 100644
--- a/studio/components/ui/MultiSelect/index.tsx
+++ b/studio/components/ui/MultiSelect/index.tsx
@@ -230,7 +230,9 @@ export default function MultiSelect({
</Popover>
</div>
- {descriptionText && <span className="form-text text-muted">{descriptionText}</span>}
+ {descriptionText && (
+ <span className="form-text text-muted text-sm mt-2">{descriptionText}</span>
+ )}
</div>
)
}
diff --git a/studio/pages/project/[ref]/settings/api.tsx b/studio/pages/project/[ref]/settings/api.tsx
index db3cb144865..37e3947aee2 100644
--- a/studio/pages/project/[ref]/settings/api.tsx
+++ b/studio/pages/project/[ref]/settings/api.tsx
@@ -6,6 +6,7 @@ import { useStore } from 'hooks'
import { NextPageWithLayout } from 'types'
import { SettingsLayout } from 'components/layouts'
import ServiceList from 'components/interfaces/Settings/API/ServiceList'
+import { FormsContainer } from 'components/ui/Forms'
export const PageContext: any = createContext(null)
@@ -37,9 +38,9 @@ const ApiSettings: NextPageWithLayout = () => {
return (
<PageContext.Provider value={PageState}>
- <div className="content h-full w-full overflow-y-auto">
+ <FormsContainer>
<ServiceList projectRef={ref as string} />
- </div>
+ </FormsContainer>
</PageContext.Provider>
)
}