The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: improve database webhooks page loading experience (#19619)
Alaister Youngc347bb0d7158
diff --git a/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx b/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsxindex 82031363d7e..26b7ed0886b 100644--- a/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx+++ b/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx@@ -93,7 +93,7 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =[data])const restUrl = project?.restUrl- const restUrlTld = new URL(restUrl as string).hostname.split('.').pop()+ const restUrlTld = restUrl ? new URL(restUrl).hostname.split('.').pop() : 'co'const isEdgeFunction = (url: string) =>url.includes(`https://${ref}.functions.supabase.${restUrlTld}/`) ||diff --git a/apps/studio/components/interfaces/Database/Hooks/HooksList/HooksList.tsx b/apps/studio/components/interfaces/Database/Hooks/HooksList/HooksList.tsxindex 06af2506be7..19b30a862ca 100644--- a/apps/studio/components/interfaces/Database/Hooks/HooksList/HooksList.tsx+++ b/apps/studio/components/interfaces/Database/Hooks/HooksList/HooksList.tsx@@ -1,19 +1,19 @@import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'import { includes, map as lodashMap, uniqBy } from 'lodash'-import { observer } from 'mobx-react-lite'import Link from 'next/link'import { useState } from 'react'import { Button, IconExternalLink, IconSearch, Input } from 'ui'import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'-import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'import AlertError from 'components/ui/AlertError'import { FormHeader } from 'components/ui/Forms'import NoSearchResults from 'components/ui/NoSearchResults'import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'import { useDatabaseHooks } from 'data/database-triggers/database-triggers-query'-import { useCheckPermissions } from 'hooks'+import { useCheckPermissions, usePermissionsLoaded } from 'hooks'+import { noop } from 'lib/void'+import HooksListEmpty from './HooksListEmpty'import SchemaTable from './SchemaTable'export interface HooksListProps {@@ -22,17 +22,14 @@ export interface HooksListProps {deleteHook: (hook: any) => void}-const HooksList = ({- createHook = () => {},- editHook = () => {},- deleteHook = () => {},-}: HooksListProps) => {+const HooksList = ({ createHook = noop, editHook = noop, deleteHook = noop }: HooksListProps) => {const { project } = useProjectContext()const {- error,data: hooks,isLoading,+ isSuccess,isError,+ error,} = useDatabaseHooks({projectRef: project?.ref,connectionString: project?.connectionString,@@ -43,105 +40,101 @@ const HooksList = ({includes(x.name.toLowerCase(), filterString.toLowerCase()))const filteredHookSchemas = lodashMap(uniqBy(filteredHooks, 'schema'), 'schema')+const canCreateWebhooks = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'triggers')+ const isPermissionsLoaded = usePermissionsLoaded()return (<>- {isLoading ? (- <div className="py-4">- <GenericSkeletonLoader />- </div>- ) : isError ? (- <AlertError error={error} subject="Failed to retrieve database webhooks" />- ) : (hooks || []).length == 0 ? (- <div className="flex h-full w-full items-center justify-center">- <ProductEmptyState- title="Database Webhooks"- ctaButtonLabel="Create Webhook"- onClickCta={() => createHook()}- disabled={!canCreateWebhooks}- disabledMessage="You need additional permissions to create webhooks"- >- <p className="text-sm text-foreground-light">- Database Webhooks can be used to trigger serverless functions or send requests to an- HTTP endpoint.- </p>- </ProductEmptyState>- </div>- ) : (- <>- <div className="flex items-center justify-between">- <FormHeader- title="Database Webhooks"- description="Send real-time data from your database to another system whenever a table event occurs"- />- </div>- <div className="w-full space-y-4">- <div className="flex items-center justify-between">- <Input- placeholder="Search for a webhook"- size="small"- icon={<IconSearch size="tiny" />}- value={filterString}- className="w-64"- onChange={(e) => setFilterString(e.target.value)}- />- <div className="flex items-center space-x-2">- <Button asChild type="default" icon={<IconExternalLink strokeWidth={1.5} />}>- <Link- href="https://supabase.com/docs/guides/database/webhooks"- target="_blank"- rel="noreferrer"- >- Documentation- </Link>+ <div className="flex items-center justify-between">+ <FormHeader+ title="Database Webhooks"+ description="Send real-time data from your database to another system whenever a table event occurs"+ />+ </div>+ <div className="w-full space-y-4">+ <div className="flex items-center justify-between">+ <Input+ placeholder="Search for a webhook"+ size="small"+ icon={<IconSearch size="tiny" />}+ value={filterString}+ className="w-64"+ onChange={(e) => setFilterString(e.target.value)}+ />+ <div className="flex items-center space-x-2">+ <Button asChild type="default" icon={<IconExternalLink strokeWidth={1.5} />}>+ <Link+ href="https://supabase.com/docs/guides/database/webhooks"+ target="_blank"+ rel="noreferrer"+ >+ Documentation+ </Link>+ </Button>+ <Tooltip.Root delayDuration={0}>+ <Tooltip.Trigger asChild>+ <Button+ disabled={!isPermissionsLoaded || !canCreateWebhooks}+ onClick={() => createHook()}+ >+ Create a new hook</Button>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <Button disabled={!canCreateWebhooks} onClick={() => createHook()}>- Create a new hook- </Button>- </Tooltip.Trigger>- {!canCreateWebhooks && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background',- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to create webhooks- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>- </div>- </div>- {filteredHooks.length <= 0 && (- <NoSearchResults- searchString={filterString}- onResetFilter={() => setFilterString('')}- />- )}- {filteredHookSchemas.map((schema: any) => (- <SchemaTable- key={schema}- filterString={filterString}- schema={schema}- editHook={editHook}- deleteHook={deleteHook}- />- ))}+ </Tooltip.Trigger>+ {isPermissionsLoaded && !canCreateWebhooks && (+ <Tooltip.Portal>+ <Tooltip.Content side="bottom">+ <Tooltip.Arrow className="radix-tooltip-arrow" />+ <div+ className={[+ 'rounded bg-alternative py-1 px-2 leading-none shadow',+ 'border border-background',+ ].join(' ')}+ >+ <span className="text-xs text-foreground">+ You need additional permissions to create webhooks+ </span>+ </div>+ </Tooltip.Content>+ </Tooltip.Portal>+ )}+ </Tooltip.Root></div>- </>- )}+ </div>++ {isLoading && (+ <div className="py-4">+ <GenericSkeletonLoader />+ </div>+ )}++ {isError && <AlertError error={error} subject="Failed to retrieve database webhooks" />}++ {isSuccess &&+ (hooks.length <= 0 ? (+ <HooksListEmpty />+ ) : (+ <>+ {filteredHooks.length <= 0 && (+ <NoSearchResults+ searchString={filterString}+ onResetFilter={() => setFilterString('')}+ />+ )}+ {filteredHookSchemas.map((schema: any) => (+ <SchemaTable+ key={schema}+ filterString={filterString}+ schema={schema}+ editHook={editHook}+ deleteHook={deleteHook}+ />+ ))}+ </>+ ))}+ </div></>)}-export default observer(HooksList)+export default HooksListdiff --git a/apps/studio/components/interfaces/Database/Hooks/HooksList/HooksListEmpty.tsx b/apps/studio/components/interfaces/Database/Hooks/HooksList/HooksListEmpty.tsxnew file mode 100644index 00000000000..2d466c0708b--- /dev/null+++ b/apps/studio/components/interfaces/Database/Hooks/HooksList/HooksListEmpty.tsx@@ -0,0 +1,38 @@+import Table from 'components/to-be-cleaned/Table'++const HooksListEmpty = () => {+ return (+ <Table+ className="table-fixed"+ head={+ <>+ <Table.th key="name" className="w-[20%]">+ <p className="translate-x-[36px]">Name</p>+ </Table.th>+ <Table.th key="table" className="w-[15%] hidden lg:table-cell">+ Table+ </Table.th>+ <Table.th key="events" className="w-[24%] hidden xl:table-cell">+ Events+ </Table.th>+ <Table.th key="webhook" className="hidden xl:table-cell">+ Webhook+ </Table.th>+ <Table.th key="buttons" className="w-[5%]"></Table.th>+ </>+ }+ body={+ <Table.tr>+ <Table.td colSpan={5}>+ <p className="text-sm text-foreground">No hooks created yet</p>+ <p className="text-sm text-foreground-light">+ Create a new hook by clicking "Create a new hook"+ </p>+ </Table.td>+ </Table.tr>+ }+ />+ )+}++export default HooksListEmptydiff --git a/apps/studio/pages/project/[ref]/database/hooks.tsx b/apps/studio/pages/project/[ref]/database/hooks.tsxindex 1df5832bacd..1ff5a7484a9 100644--- a/apps/studio/pages/project/[ref]/database/hooks.tsx+++ b/apps/studio/pages/project/[ref]/database/hooks.tsx@@ -1,6 +1,6 @@import { PermissionAction } from '@supabase/shared-types/out/constants'-import { observer } from 'mobx-react-lite'-import { useEffect, useState } from 'react'+import { useState } from 'react'+import toast from 'react-hot-toast'import { useParams } from 'common'import DeleteHookModal from 'components/interfaces/Database/Hooks/DeleteHookModal'@@ -13,19 +13,17 @@ import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'import NoPermission from 'components/ui/NoPermission'import { useHooksEnableMutation } from 'data/database/hooks-enable-mutation'import { useSchemasQuery } from 'data/database/schemas-query'-import { useCheckPermissions, usePermissionsLoaded, useStore } from 'hooks'+import { useCheckPermissions, usePermissionsLoaded } from 'hooks'import { NextPageWithLayout } from 'types'-import { IconLoader } from 'ui'const HooksPage: NextPageWithLayout = () => {const { project } = useProjectContext()- const { meta, ui } = useStore()const { ref: projectRef } = useParams()const {data: schemas,- isLoading: isLoadingSchemas,+ isSuccess: isSchemasLoaded,refetch,} = useSchemasQuery({projectRef: project?.ref,@@ -44,17 +42,10 @@ const HooksPage: NextPageWithLayout = () => {const { mutate: enableHooks, isLoading: isEnablingHooks } = useHooksEnableMutation({onSuccess: () => {refetch()- ui.setNotification({- category: 'success',- message: `Successfully enabled webhooks`,- })+ toast.success('Successfully enabled webhooks')},})- useEffect(() => {- if (ui.selectedProjectRef) meta.hooks.load()- }, [ui.selectedProjectRef])-const enableHooksForProject = async () => {if (!projectRef) return console.error('Project ref is required')enableHooks({ ref: projectRef })@@ -79,16 +70,7 @@ const HooksPage: NextPageWithLayout = () => {return <NoPermission isFullPage resourceText="view database webhooks" />}- if (isLoadingSchemas) {- return (- <div className="w-full h-full flex items-center justify-center space-x-2">- <IconLoader className="animate-spin" size="tiny" strokeWidth={1.5} />- <p className="text-sm text-foreground-light">Checking if hooks are enabled</p>- </div>- )- }-- if (!isHooksEnabled) {+ if (isSchemasLoaded && !isHooksEnabled) {return (<div className="w-full h-full flex items-center justify-center"><ProductEmptyState@@ -97,9 +79,11 @@ const HooksPage: NextPageWithLayout = () => {ctaButtonLabel="Enable webhooks"onClickCta={() => enableHooksForProject()}loading={isEnablingHooks}- disabled={isEnablingHooks || !canCreateWebhooks}+ disabled={isEnablingHooks || (isPermissionsLoaded && !canReadWebhooks)}disabledMessage={- !canCreateWebhooks ? 'You need additional permissions to enable webhooks' : undefined+ isPermissionsLoaded && !canCreateWebhooks+ ? 'You need additional permissions to enable webhooks'+ : undefined}><p className="text-sm text-foreground-light">@@ -137,4 +121,4 @@ const HooksPage: NextPageWithLayout = () => {HooksPage.getLayout = (page) => <DatabaseLayout title="Hooks">{page}</DatabaseLayout>-export default observer(HooksPage)+export default HooksPagediff --git a/apps/studio/stores/pgmeta/HooksStore.ts b/apps/studio/stores/pgmeta/HooksStore.tsdeleted file mode 100644index 49218fe16f6..00000000000--- a/apps/studio/stores/pgmeta/HooksStore.ts+++ /dev/null@@ -1,29 +0,0 @@-import PostgresMetaInterface from '../common/PostgresMetaInterface'-import { IRootStore } from '../RootStore'--export default class HooksStore extends PostgresMetaInterface<any> {- constructor(- rootStore: IRootStore,- dataUrl: string,- headers?: {- [prop: string]: any- },- options?: { identifier: string }- ) {- super(rootStore, dataUrl, headers, options)- }-- /**- * Get a list of all hooks data in the store as an array- * @param filter A custom filter (eg: (x) => x.name === 'name')- * @param options.allSchemas If true, will include "excluded" schemas- */- list(filter: any) {- const hooksFilter = (h: any) =>- h.function_schema === 'supabase_functions' &&- h.schema !== 'net' &&- (typeof filter === 'function' ? filter(h) : true)-- return super.list(hooksFilter)- }-}diff --git a/apps/studio/stores/pgmeta/MetaStore.ts b/apps/studio/stores/pgmeta/MetaStore.tsindex 55ba1460d40..9963d087b1a 100644--- a/apps/studio/stores/pgmeta/MetaStore.ts+++ b/apps/studio/stores/pgmeta/MetaStore.ts@@ -41,7 +41,6 @@ import { getTables } from 'data/tables/tables-query'import ExtensionsStore from './ExtensionsStore'import ForeignTableStore, { IForeignTableStore } from './ForeignTableStore'import FunctionsStore from './FunctionsStore'-import HooksStore from './HooksStore'import MaterializedViewStore, { IMaterializedViewStore } from './MaterializedViewStore'import PoliciesStore from './PoliciesStore'import PublicationStore from './PublicationStore'@@ -60,7 +59,6 @@ export interface IMetaStore {materializedViews: IMaterializedViewStoreforeignTables: IForeignTableStore- hooks: IPostgresMetaInterface<any>roles: IRolesStorepolicies: IPostgresMetaInterface<any>triggers: IPostgresMetaInterface<any>@@ -151,7 +149,6 @@ export default class MetaStore implements IMetaStore {materializedViews: MaterializedViewStoreforeignTables: ForeignTableStore- hooks: HooksStoreroles: RolesStorepolicies: PoliciesStoretriggers: TriggersStore@@ -196,7 +193,6 @@ export default class MetaStore implements IMetaStore {this.roles = new RolesStore(this.rootStore, `${this.baseUrl}/roles`, this.headers)this.policies = new PoliciesStore(this.rootStore, `${this.baseUrl}/policies`, this.headers)- this.hooks = new HooksStore(this.rootStore, `${this.baseUrl}/triggers`, this.headers)this.triggers = new TriggersStore(this.rootStore, `${this.baseUrl}/triggers`, this.headers)this.functions = new FunctionsStore(this.rootStore, `${this.baseUrl}/functions`, this.headers)this.extensions = new ExtensionsStore(@@ -1001,9 +997,6 @@ export default class MetaStore implements IMetaStore {this.policies.setUrl(`${this.baseUrl}/policies`)this.policies.setHeaders(this.headers)- this.hooks.setUrl(`${this.baseUrl}/triggers`)- this.hooks.setHeaders(this.headers)-this.triggers.setUrl(`${this.baseUrl}/triggers`)this.triggers.setHeaders(this.headers)