Skip to content

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

fix: Fix a "webhook not found" error when editing a web hook (#42428)

Ivan Vasilov473619bece7c
diff --git a/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.constants.ts b/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.constants.ts
new file mode 100644
index 00000000000..fb991e2c17b
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.constants.ts
@@ -0,0 +1,38 @@
+import { z } from 'zod'
+
+import { isValidHttpUrl } from '@/lib/helpers'
+
+const httpRequestSchema = z.object({
+ function_type: z.literal('http_request'),
+ http_url: z
+ .string()
+ .min(1, 'Please provide a URL')
+ .refine((val) => val.startsWith('http'), 'Please prefix your URL with http or https')
+ .refine((val) => isValidHttpUrl(val), 'Please provide a valid URL'),
+})
+
+const supabaseFunctionSchema = z.object({
+ function_type: z.literal('supabase_function'),
+ http_url: z
+ .string()
+ .min(1, 'Please select an edge function')
+ .refine((val) => !val.includes('undefined'), 'No edge functions available for selection'),
+})
+
+export const FormSchema = z
+ .object({
+ name: z.string().min(1, 'Please provide a name for your webhook'),
+ table_id: z.string().min(1, 'Please select a table'),
+ http_method: z.enum(['GET', 'POST']),
+ timeout_ms: z.coerce
+ .number()
+ .int()
+ .gte(1000, 'Timeout should be at least 1000ms')
+ .lte(10000, 'Timeout should not exceed 10,000ms'),
+ events: z.array(z.string()).min(1, 'Please select at least one event'),
+ httpHeaders: z.array(z.object({ id: z.string(), name: z.string(), value: z.string() })),
+ httpParameters: z.array(z.object({ id: z.string(), name: z.string(), value: z.string() })),
+ })
+ .and(z.discriminatedUnion('function_type', [httpRequestSchema, supabaseFunctionSchema]))
+
+export type WebhookFormValues = z.infer<typeof FormSchema>
diff --git a/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx b/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx
index 479c4e96049..f4f43edf078 100644
--- a/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx
+++ b/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx
@@ -1,19 +1,22 @@
+import { zodResolver } from '@hookform/resolvers/zod'
import { PGTriggerCreate } from '@supabase/pg-meta/src/pg-meta-triggers'
import type { PostgresTrigger } from '@supabase/postgres-meta'
-import { useEffect, useMemo, useRef, useState } from 'react'
-import { toast } from 'sonner'
-
+import { useQueryClient } from '@tanstack/react-query'
import { useParams } from 'common'
-import { useDatabaseTriggerCreateMutation } from 'data/database-triggers/database-trigger-create-mutation'
-import { useDatabaseTriggerUpdateMutation } from 'data/database-triggers/database-trigger-update-transaction-mutation'
-import { getTableEditor } from 'data/table-editor/table-editor-query'
-import { useTablesQuery } from 'data/tables/tables-query'
-import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
-import { useConfirmOnClose, type ConfirmOnCloseModalProps } from 'hooks/ui/useConfirmOnClose'
-import { isValidHttpUrl, uuidv4 } from 'lib/helpers'
-import { Button, Form, SidePanel } from 'ui'
+import { useEffect, useState } from 'react'
+import { SubmitHandler, useForm } from 'react-hook-form'
+import { toast } from 'sonner'
+import { Button, Form_Shadcn_, SidePanel } from 'ui'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
+
+import { FormSchema, WebhookFormValues } from './EditHookPanel.constants'
import { FormContents } from './FormContents'
+import { useDatabaseTriggerCreateMutation } from '@/data/database-triggers/database-trigger-create-mutation'
+import { useDatabaseTriggerUpdateMutation } from '@/data/database-triggers/database-trigger-update-transaction-mutation'
+import { tableEditorQueryOptions } from '@/data/table-editor/table-editor-query'
+import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
+import { useConfirmOnClose, type ConfirmOnCloseModalProps } from '@/hooks/ui/useConfirmOnClose'
+import { uuidv4 } from '@/lib/helpers'
export interface EditHookPanelProps {
visible: boolean
@@ -35,236 +38,218 @@ export const isEdgeFunction = ({
url.includes(`https://${ref}.functions.supabase.${restUrlTld}/`) ||
url.includes(`https://${ref}.supabase.${restUrlTld}/functions/`)
-export const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) => {
- const { ref } = useParams()
- const submitRef = useRef<any>(null)
- const [isEdited, setIsEdited] = useState(false)
-
- // [Joshen] There seems to be some bug between Checkbox.Group within the Form component
- // hence why this external state as a temporary workaround
- const [events, setEvents] = useState<string[]>(selectedHook?.events ?? [])
- const [eventsError, setEventsError] = useState<string>()
- const [isSubmitting, setIsSubmitting] = useState(false)
+const FORM_ID = 'edit-hook-panel-form'
- // For HTTP request
- const [httpHeaders, setHttpHeaders] = useState<HTTPArgument[]>(() => {
- if (typeof selectedHook === `undefined`) {
- return [{ id: uuidv4(), name: 'Content-type', value: 'application/json' }]
- }
- const [_, __, headers] = selectedHook.function_args
- let parsedHeaders: Record<string, string> = {}
+const parseHeaders = (selectedHook?: PostgresTrigger): HTTPArgument[] => {
+ if (typeof selectedHook === 'undefined') {
+ return [{ id: uuidv4(), name: 'Content-type', value: 'application/json' }]
+ }
+ const [, , headers] = selectedHook.function_args
+ let parsedHeaders: Record<string, string> = {}
- try {
- parsedHeaders = JSON.parse(headers.replace(/\\"/g, '"'))
- } catch (e) {
- parsedHeaders = {}
- }
+ try {
+ parsedHeaders = JSON.parse(headers.replace(/\\"/g, '"'))
+ } catch (e) {
+ parsedHeaders = {}
+ }
- return Object.entries(parsedHeaders).map(([name, value]) => ({
- id: uuidv4(),
- name,
- value,
- }))
- })
+ return Object.entries(parsedHeaders).map(([name, value]) => ({
+ id: uuidv4(),
+ name,
+ value,
+ }))
+}
- const [httpParameters, setHttpParameters] = useState<HTTPArgument[]>(() => {
- if (typeof selectedHook === `undefined`) {
- return [{ id: uuidv4(), name: '', value: '' }]
- }
- const [_, __, ___, parameters] = selectedHook.function_args
- let parsedParameters: Record<string, string> = {}
+const parseParameters = (selectedHook?: PostgresTrigger): HTTPArgument[] => {
+ if (typeof selectedHook === 'undefined') {
+ return [{ id: uuidv4(), name: '', value: '' }]
+ }
+ const [, , , parameters] = selectedHook.function_args
+ let parsedParameters: Record<string, string> = {}
- try {
- parsedParameters = JSON.parse(parameters.replace(/\\"/g, '"'))
- } catch (e) {
- parsedParameters = {}
- }
+ try {
+ parsedParameters = JSON.parse(parameters.replace(/\\"/g, '"'))
+ } catch (e) {
+ parsedParameters = {}
+ }
- return Object.entries(parsedParameters).map(([name, value]) => ({
- id: uuidv4(),
- name,
- value,
- }))
- })
+ return Object.entries(parsedParameters).map(([name, value]) => ({
+ id: uuidv4(),
+ name,
+ value,
+ }))
+}
+export const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) => {
+ const { ref } = useParams()
const { data: project } = useSelectedProjectQuery()
- const { data } = useTablesQuery({
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- })
-
- const { mutate: createDatabaseTrigger } = useDatabaseTriggerCreateMutation({
- onSuccess: (res) => {
- toast.success(`Successfully created new webhook "${res.name}"`)
- setIsSubmitting(false)
- onClose()
- },
- onError: (error) => {
- setIsSubmitting(false)
- toast.error(`Failed to create webhook: ${error.message}`)
- },
- })
-
- const { mutate: updateDatabaseTrigger } = useDatabaseTriggerUpdateMutation({
- onSuccess: (res) => {
- setIsSubmitting(false)
- toast.success(`Successfully updated webhook "${res.name}"`)
- onClose()
- },
- onError: (error) => {
- setIsSubmitting(false)
- toast.error(`Failed to update webhook: ${error.message}`)
- },
- })
-
- const tables = useMemo(
- () => [...(data ?? [])].sort((a, b) => (a.schema > b.schema ? 0 : -1)),
- [data]
+ const [isLoadingTable, setIsLoadingTable] = useState(false)
+
+ const { mutate: createDatabaseTrigger, isPending: isCreating } = useDatabaseTriggerCreateMutation(
+ {
+ onSuccess: (res) => {
+ toast.success(`Successfully created new webhook "${res.name}"`)
+ onClose()
+ },
+ onError: (error) => {
+ toast.error(`Failed to create webhook: ${error.message}`)
+ },
+ }
)
- const restUrl = project?.restUrl
- const restUrlTld = restUrl ? new URL(restUrl).hostname.split('.').pop() : 'co'
-
- const initialValues = {
- name: selectedHook?.name ?? '',
- table_id: selectedHook?.table_id ?? '',
- http_url: selectedHook?.function_args?.[0] ?? '',
- http_method: selectedHook?.function_args?.[1] ?? 'POST',
- function_type: isEdgeFunction({ ref, restUrlTld, url: selectedHook?.function_args?.[0] ?? '' })
- ? 'supabase_function'
- : 'http_request',
- timeout_ms: Number(selectedHook?.function_args?.[4] ?? 5000),
- }
- const onUpdateSelectedEvents = (event: string) => {
- if (events.includes(event)) {
- setEvents(events.filter((e) => e !== event))
- } else {
- setEvents(events.concat(event))
+ const { mutate: updateDatabaseTrigger, isPending: isUpdating } = useDatabaseTriggerUpdateMutation(
+ {
+ onSuccess: (res) => {
+ toast.success(`Successfully updated webhook "${res.name}"`)
+ onClose()
+ },
+ onError: (error) => {
+ toast.error(`Failed to update webhook: ${error.message}`)
+ },
}
- setEventsError(undefined)
- }
+ )
- const validate = (values: any) => {
- const errors: any = {}
+ const isSubmitting = isCreating || isUpdating || isLoadingTable
- if (!values.name) {
- errors['name'] = 'Please provide a name for your webhook'
- }
- if (!values.table_id) {
- errors['table_id'] = 'Please select a table for which your webhook will trigger from'
- }
+ const restUrl = project?.restUrl
+ const restUrlTld = restUrl ? new URL(restUrl).hostname.split('.').pop() : 'co'
- if (values.function_type === 'http_request') {
- // For HTTP requests
- if (!values.http_url) {
- errors['http_url'] = 'Please provide a URL'
- } else if (!values.http_url.startsWith('http')) {
- errors['http_url'] = 'Please include HTTP/HTTPs to your URL'
- } else if (!isValidHttpUrl(values.http_url)) {
- errors['http_url'] = 'Please provide a valid URL'
- }
- } else if (values.function_type === 'supabase_function') {
- // For Supabase Edge Functions
- if (values.http_url.includes('undefined')) {
- errors['http_url'] = 'No edge functions available for selection'
- }
- }
+ const form = useForm<WebhookFormValues>({
+ resolver: zodResolver(FormSchema),
+ defaultValues: {
+ name: selectedHook?.name ?? '',
+ table_id: selectedHook?.table_id?.toString() ?? '',
+ http_url: selectedHook?.function_args?.[0] ?? '',
+ http_method: (selectedHook?.function_args?.[1] as 'GET' | 'POST') ?? 'POST',
+ function_type: isEdgeFunction({
+ ref,
+ restUrlTld,
+ url: selectedHook?.function_args?.[0] ?? '',
+ })
+ ? 'supabase_function'
+ : 'http_request',
+ timeout_ms: Number(selectedHook?.function_args?.[4] ?? 5000),
+ events: selectedHook?.events ?? [],
+ httpHeaders: parseHeaders(selectedHook),
+ httpParameters: parseParameters(selectedHook),
+ },
+ })
- if (values.timeout_ms < 1000 || values.timeout_ms > 10_000) {
- errors['timeout_ms'] = 'Timeout should be between 1000ms and 10,000ms'
+ // Reset form when panel opens with new selectedHook
+ useEffect(() => {
+ if (visible) {
+ form.reset({
+ name: selectedHook?.name ?? '',
+ table_id: selectedHook?.table_id?.toString() ?? '',
+ http_url: selectedHook?.function_args?.[0] ?? '',
+ http_method: (selectedHook?.function_args?.[1] as 'GET' | 'POST') ?? 'POST',
+ function_type: isEdgeFunction({
+ ref,
+ restUrlTld,
+ url: selectedHook?.function_args?.[0] ?? '',
+ })
+ ? 'supabase_function'
+ : 'http_request',
+ timeout_ms: Number(selectedHook?.function_args?.[4] ?? 5000),
+ events: selectedHook?.events ?? [],
+ httpHeaders: parseHeaders(selectedHook),
+ httpParameters: parseParameters(selectedHook),
+ })
}
+ }, [visible, selectedHook, ref, restUrlTld, form])
- if (JSON.stringify(values) !== JSON.stringify(initialValues)) setIsEdited(true)
- return errors
- }
-
- const onSubmit = async (values: any) => {
- setIsSubmitting(true)
+ const queryClient = useQueryClient()
+ const onSubmit: SubmitHandler<WebhookFormValues> = async (values) => {
if (!project?.ref) {
return console.error('Project ref is required')
}
- if (events.length === 0) {
- return setEventsError('Please select at least one event')
- }
- const selectedTable = await getTableEditor({
- id: values.table_id,
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- })
- if (!selectedTable) {
- setIsSubmitting(false)
- return toast.error('Unable to find selected table')
- }
-
- const headers = httpHeaders
- .filter((header) => header.name && header.value)
- .reduce((a: any, b: any) => {
- a[b.name] = b.value
- return a
- }, {})
- const parameters = httpParameters
- .filter((param) => param.name && param.value)
- .reduce((a: any, b: any) => {
- a[b.name] = b.value
- return a
- }, {})
+ try {
+ setIsLoadingTable(true)
+ const selectedTable = await queryClient.fetchQuery(
+ tableEditorQueryOptions({
+ id: Number(values.table_id),
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+ )
+ if (!selectedTable) {
+ return toast.error('Unable to find selected table')
+ }
- // replacer function with JSON.stringify to handle quotes properly
- const stringifiedParameters = JSON.stringify(parameters, (key, value) => {
- if (typeof value === 'string') {
- // Return the raw string without any additional escaping
+ const headers = values.httpHeaders
+ .filter((header) => header.name && header.value)
+ .reduce(
+ (a, b) => {
+ a[b.name] = b.value
+ return a
+ },
+ {} as Record<string, string>
+ )
+ const parameters = values.httpParameters
+ .filter((param) => param.name && param.value)
+ .reduce(
+ (a, b) => {
+ a[b.name] = b.value
+ return a
+ },
+ {} as Record<string, string>
+ )
+
+ // replacer function with JSON.stringify to handle quotes properly
+ const stringifiedParameters = JSON.stringify(parameters, (key, value) => {
+ if (typeof value === 'string') {
+ // Return the raw string without any additional escaping
+ return value
+ }
return value
- }
- return value
- })
+ })
- const payload: PGTriggerCreate = {
- events,
- activation: 'AFTER',
- orientation: 'ROW',
- name: values.name,
- table: selectedTable.name,
- schema: selectedTable.schema,
- function_name: 'http_request',
- function_schema: 'supabase_functions',
- function_args: [
- values.http_url,
- values.http_method,
- JSON.stringify(headers),
- stringifiedParameters,
- values.timeout_ms.toString(),
- ],
- }
+ const payload: PGTriggerCreate = {
+ events: values.events,
+ activation: 'AFTER',
+ orientation: 'ROW',
+ name: values.name,
+ table: selectedTable.name,
+ schema: selectedTable.schema,
+ function_name: 'http_request',
+ function_schema: 'supabase_functions',
+ function_args: [
+ values.http_url,
+ values.http_method,
+ JSON.stringify(headers),
+ stringifiedParameters,
+ values.timeout_ms.toString(),
+ ],
+ }
- if (selectedHook === undefined) {
- createDatabaseTrigger({
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- payload,
- })
- } else {
- updateDatabaseTrigger({
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- originalTrigger: selectedHook,
- updatedTrigger: { ...payload, enabled_mode: 'ORIGIN' },
- })
+ if (selectedHook === undefined) {
+ createDatabaseTrigger({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ payload,
+ })
+ } else {
+ updateDatabaseTrigger({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ originalTrigger: selectedHook,
+ updatedTrigger: { ...payload, enabled_mode: 'ORIGIN' },
+ })
+ }
+ } catch (error) {
+ console.error('Failed to get table editor:', error)
+ toast.error('Failed to get table editor')
+ } finally {
+ setIsLoadingTable(false)
}
}
- useEffect(() => {
- if (visible) {
- setIsEdited(false)
- }
- }, [visible])
-
+ // This is intentionally kept outside of the useConfirmOnClose hook to force RHF to update the isDirty state.
+ const isDirty = form.formState.isDirty
const { confirmOnClose, modalProps: closeConfirmationModalProps } = useConfirmOnClose({
- checkIsDirty: () => isEdited,
- onClose: () => {
- setIsEdited(false)
- onClose()
- },
+ checkIsDirty: () => isDirty,
+ onClose: () => onClose(),
})
return (
@@ -298,37 +283,21 @@ export const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelP
<Button
size="tiny"
type="primary"
- htmlType="button"
+ htmlType="submit"
+ form={FORM_ID}
disabled={isSubmitting}
loading={isSubmitting}
- onClick={() => submitRef?.current?.click()}
>
{selectedHook === undefined ? 'Create webhook' : 'Update webhook'}
</Button>
</div>
}
>
- <Form validateOnBlur initialValues={initialValues} onSubmit={onSubmit} validate={validate}>
- {({ values, resetForm, errors }: any) => {
- return (
- <FormContents
- values={values}
- resetForm={resetForm}
- errors={errors}
- tables={tables}
- events={events}
- eventsError={eventsError}
- onUpdateSelectedEvents={onUpdateSelectedEvents}
- httpHeaders={httpHeaders}
- httpParameters={httpParameters}
- setHttpHeaders={setHttpHeaders}
- setHttpParameters={setHttpParameters}
- submitRef={submitRef}
- selectedHook={selectedHook}
- />
- )
- }}
- </Form>
+ <Form_Shadcn_ {...form}>
+ <form id={FORM_ID} onSubmit={form.handleSubmit(onSubmit)}>
+ <FormContents form={form} selectedHook={selectedHook} />
+ </form>
+ </Form_Shadcn_>
</SidePanel>
<CloseConfirmationModal {...closeConfirmationModalProps} />
</>
diff --git a/apps/studio/components/interfaces/Database/Hooks/FormContents.tsx b/apps/studio/components/interfaces/Database/Hooks/FormContents.tsx
index 834e78113c2..a74690c7d35 100644
--- a/apps/studio/components/interfaces/Database/Hooks/FormContents.tsx
+++ b/apps/studio/components/interfaces/Database/Hooks/FormContents.tsx
@@ -1,51 +1,51 @@
-import type { PostgresTable, PostgresTrigger } from '@supabase/postgres-meta'
+import type { PostgresTrigger } from '@supabase/postgres-meta'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useParams } from 'common'
import Image from 'next/legacy/image'
-import { MutableRefObject, useEffect } from 'react'
+import { useEffect, useMemo } from 'react'
+import { UseFormReturn } from 'react-hook-form'
+import {
+ Checkbox_Shadcn_,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ Input_Shadcn_,
+ Label_Shadcn_,
+ RadioGroupStacked,
+ RadioGroupStackedItem,
+ Select_Shadcn_,
+ SelectContent_Shadcn_,
+ SelectItem_Shadcn_,
+ SelectTrigger_Shadcn_,
+ SelectValue_Shadcn_,
+ SidePanel,
+ useWatch_Shadcn_,
+} from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
-import { useParams } from 'common'
-import { FormSection, FormSectionContent, FormSectionLabel } from 'components/ui/Forms/FormSection'
-import { useAPIKeysQuery } from 'data/api-keys/api-keys-query'
-import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'
-import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
-import { uuidv4 } from 'lib/helpers'
-import { Checkbox, Input, Listbox, Radio, SidePanel } from 'ui'
-import { HTTPArgument, isEdgeFunction } from './EditHookPanel'
-import HTTPRequestFields from './HTTPRequestFields'
+import { isEdgeFunction } from './EditHookPanel'
+import { WebhookFormValues } from './EditHookPanel.constants'
import { AVAILABLE_WEBHOOK_TYPES, HOOK_EVENTS } from './Hooks.constants'
+import { HTTPHeaders } from './HTTPHeaders'
+import { HTTPParameters } from './HTTPParameters'
+import { HTTPRequestConfig } from './HTTPRequestConfig'
+import {
+ FormSection,
+ FormSectionContent,
+ FormSectionLabel,
+} from '@/components/ui/Forms/FormSection'
+import { useAPIKeysQuery } from '@/data/api-keys/api-keys-query'
+import { useEdgeFunctionsQuery } from '@/data/edge-functions/edge-functions-query'
+import { useTablesQuery } from '@/data/tables/tables-query'
+import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
+import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
+import { uuidv4 } from '@/lib/helpers'
export interface FormContentsProps {
- values: any
- resetForm: any
- errors: any
+ form: UseFormReturn<WebhookFormValues>
selectedHook?: PostgresTrigger
- tables: PostgresTable[]
- events: string[]
- eventsError?: string
- onUpdateSelectedEvents: (event: string) => void
- httpHeaders: HTTPArgument[]
- httpParameters: HTTPArgument[]
- setHttpHeaders: (arr: HTTPArgument[]) => void
- setHttpParameters: (arr: HTTPArgument[]) => void
- submitRef: MutableRefObject<any>
}
-export const FormContents = ({
- values,
- resetForm,
- errors,
- selectedHook,
- tables,
- events,
- eventsError,
- onUpdateSelectedEvents,
- httpHeaders,
- httpParameters,
- setHttpHeaders,
- setHttpParameters,
- submitRef,
-}: FormContentsProps) => {
+export const FormContents = ({ form, selectedHook }: FormContentsProps) => {
const { ref } = useParams()
const { data: project } = useSelectedProjectQuery()
@@ -63,69 +63,64 @@ export const FormContents = ({
const legacyServiceRole = keys.find((x) => x.name === 'service_role')?.api_key ?? '[YOUR API KEY]'
- useEffect(() => {
- if (values.function_type === 'http_request') {
- if (selectedHook !== undefined) {
- const [url, method] = selectedHook.function_args
- const updatedValues = { ...values, http_url: url, http_method: method }
- resetForm({ values: updatedValues, initialValues: updatedValues })
- } else {
- const updatedValues = { ...values, http_url: '' }
- resetForm({ values: updatedValues, initialValues: updatedValues })
- }
- } else if (values.function_type === 'supabase_function') {
- // Default to first edge function in the list
- const fnSlug = functions[0]?.slug
- const defaultFunctionUrl = `https://${ref}.supabase.${restUrlTld}/functions/v1/${fnSlug}`
- const updatedValues = {
- ...values,
- http_url: isEdgeFunction({ ref, restUrlTld, url: values.http_url })
- ? values.http_url
- : defaultFunctionUrl,
- }
- resetForm({ values: updatedValues, initialValues: updatedValues })
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [values.function_type])
+ const httpUrl = useWatch_Shadcn_({ control: form.control, name: 'http_url' })
+ const httpHeaders = useWatch_Shadcn_({ control: form.control, name: 'httpHeaders' })
+
+ const { data } = useTablesQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const tables = useMemo(
+ () => [...(data ?? [])].sort((a, b) => (a.schema > b.schema ? 0 : -1)),
+ [data]
+ )
+ // Handle auth header auto-add for edge functions
useEffect(() => {
if (!isSuccessEdgeFunctions) return
- const isEdgeFunctionSelected = isEdgeFunction({ ref, restUrlTld, url: values.http_url })
+ const isEdgeFunctionSelected = isEdgeFunction({ ref, restUrlTld, url: httpUrl })
- if (values.http_url && isEdgeFunctionSelected) {
- const fnSlug = values.http_url.split('/').at(-1)
+ if (httpUrl && isEdgeFunctionSelected) {
+ const fnSlug = httpUrl.split('/').at(-1)
const fn = functions.find((x) => x.slug === fnSlug)
const authorizationHeader = httpHeaders.find((x) => x.name === 'Authorization')
const edgeFunctionAuthHeaderVal = `Bearer ${legacyServiceRole}`
if (fn?.verify_jwt && authorizationHeader == null) {
- const authorizationHeader = {
+ const newAuthHeader = {
id: uuidv4(),
name: 'Authorization',
value: edgeFunctionAuthHeaderVal,
}
- setHttpHeaders([...httpHeaders, authorizationHeader])
+ form.setValue('httpHeaders', [...httpHeaders, newAuthHeader])
} else if (fn?.verify_jwt && authorizationHeader?.value !== edgeFunctionAuthHeaderVal) {
const updatedHttpHeaders = httpHeaders.map((x) => {
if (x.name === 'Authorization') return { ...x, value: edgeFunctionAuthHeaderVal }
else return x
})
- setHttpHeaders(updatedHttpHeaders)
+ form.setValue('httpHeaders', updatedHttpHeaders)
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [values.http_url, isSuccessEdgeFunctions])
+ }, [httpUrl, isSuccessEdgeFunctions])
return (
<div>
<FormSection header={<FormSectionLabel className="lg:!col-span-4">General</FormSectionLabel>}>
<FormSectionContent loading={false} className="lg:!col-span-8">
- <Input
- id="name"
+ <FormField_Shadcn_
+ control={form.control}
name="name"
- label="Name"
- descriptionText="Do not use spaces/whitespaces"
+ render={({ field }) => (
+ <FormItemLayout label="Name" layout="vertical" className="gap-1">
+ <FormControl_Shadcn_>
+ <Input_Shadcn_ {...field} placeholder="my_webhook" />
+ </FormControl_Shadcn_>
+ <p className="text-xs text-foreground-lighter">Do not use spaces/whitespaces</p>
+ </FormItemLayout>
+ )}
/>
</FormSectionContent>
</FormSection>
@@ -145,53 +140,76 @@ export const FormContents = ({
}
>
<FormSectionContent loading={false} className="lg:!col-span-8">
- <Listbox
- size="medium"
- id="table_id"
+ <FormField_Shadcn_
+ control={form.control}
name="table_id"
- label="Table"
- descriptionText="This is the table the trigger will watch for changes. You can only select 1 table for a trigger."
- >
- <Listbox.Option
- key={'table-no-selection'}
- id={'table-no-selection'}
- label={'---'}
- value={'no-selection'}
- >
- ---
- </Listbox.Option>
- {tables.map((table) => (
- <Listbox.Option
- key={table.id}
- id={table.id.toString()}
- value={table.id}
- label={table.name}
+ render={({ field }) => (
+ <FormItemLayout
+ label="Table"
+ layout="vertical"
+ className="gap-1"
+ description="This is the table the trigger will watch for changes. You can only select 1 table for a trigger."
>
- <div className="flex items-center space-x-2">
- <p className="text-foreground-light">{table.schema}</p>
- <p className="text-foreground">{table.name}</p>
- </div>
- </Listbox.Option>
- ))}
- </Listbox>
- <Checkbox.Group
- id="events"
+ <Select_Shadcn_ value={field.value} onValueChange={field.onChange}>
+ <FormControl_Shadcn_>
+ <SelectTrigger_Shadcn_>
+ <SelectValue_Shadcn_ placeholder="Select a table" />
+ </SelectTrigger_Shadcn_>
+ </FormControl_Shadcn_>
+ <SelectContent_Shadcn_>
+ {tables.map((table) => (
+ <SelectItem_Shadcn_ key={table.id} value={table.id.toString()}>
+ <div className="flex items-center space-x-2">
+ <span className="text-foreground-light">{table.schema}</span>
+ <span className="text-foreground">{table.name}</span>
+ </div>
+ </SelectItem_Shadcn_>
+ ))}
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+
+ <FormField_Shadcn_
+ control={form.control}
name="events"
- label="Events"
- error={eventsError}
- descriptionText="These are the events that are watched by the webhook, only the events selected above will fire the webhook on the table you've selected."
- >
- {HOOK_EVENTS.map((event) => (
- <Checkbox
- key={event.value}
- value={event.value}
- label={event.label}
- description={event.description}
- checked={events.includes(event.value)}
- onChange={() => onUpdateSelectedEvents(event.value)}
- />
- ))}
- </Checkbox.Group>
+ render={({ field }) => (
+ <FormItemLayout
+ label="Events"
+ layout="vertical"
+ className="gap-1"
+ description="These are the events that are watched by the webhook, only the events selected above will fire the webhook on the table you've selected."
+ >
+ <div className="space-y-3">
+ {HOOK_EVENTS.map((event) => (
+ <div key={event.value} className="flex items-start space-x-3">
+ <Checkbox_Shadcn_
+ id={`event-${event.value}`}
+ checked={field.value.includes(event.value)}
+ onCheckedChange={(checked) => {
+ if (checked) {
+ field.onChange([...field.value, event.value])
+ } else {
+ field.onChange(field.value.filter((v) => v !== event.value))
+ }
+ }}
+ />
+ <div className="grid gap-1.5 leading-none">
+ <Label_Shadcn_
+ htmlFor={`event-${event.value}`}
+ className="text-sm font-normal cursor-pointer"
+ >
+ {event.label}
+ </Label_Shadcn_>
+ <p className="text-xs text-foreground-lighter">{event.description}</p>
+ </div>
+ </div>
+ ))}
+ </div>
+ </FormItemLayout>
+ )}
+ />
</FormSectionContent>
</FormSection>
<SidePanel.Separator />
@@ -201,70 +219,72 @@ export const FormContents = ({
}
>
<FormSectionContent loading={false} className="lg:!col-span-8">
- <Radio.Group id="function_type" name="function_type" label="Type of webhook" type="cards">
- {AVAILABLE_WEBHOOK_TYPES.map((webhook) => (
- <Radio
- key={webhook.value}
- id={webhook.value}
- value={webhook.value}
- label=""
- beforeLabel={
- <div className="flex items-center space-x-5">
- <Image
- alt={webhook.label}
- src={webhook.icon}
- layout="fixed"
- width="32"
- height="32"
- />
- <div className="flex-col space-y-0">
- <div className="flex space-x-2">
- <p className="text-foreground">{webhook.label}</p>
- </div>
- <p className="text-foreground-light">{webhook.description}</p>
- </div>
- </div>
- }
- />
- ))}
- </Radio.Group>
+ <FormField_Shadcn_
+ control={form.control}
+ name="function_type"
+ render={({ field }) => (
+ <FormItemLayout label="Type of webhook" layout="vertical" className="gap-1">
+ <FormControl_Shadcn_>
+ <RadioGroupStacked
+ value={field.value}
+ onValueChange={(functionType) => {
+ if (functionType === 'http_request') {
+ if (selectedHook !== undefined) {
+ const [url] = selectedHook.function_args
+ form.setValue('http_url', url, { shouldDirty: false })
+ } else {
+ form.setValue('http_url', '', { shouldDirty: false })
+ }
+ } else if (functionType === 'supabase_function') {
+ // Default to first edge function in the list
+ const fnSlug = functions[0]?.slug
+ const defaultFunctionUrl = `https://${ref}.supabase.${restUrlTld}/functions/v1/${fnSlug}`
+ const currentUrl = form.getValues('http_url')
+ if (!isEdgeFunction({ ref, restUrlTld, url: currentUrl })) {
+ form.setValue('http_url', defaultFunctionUrl, { shouldDirty: false })
+ }
+ }
+ field.onChange(functionType)
+ }}
+ >
+ {AVAILABLE_WEBHOOK_TYPES.map((webhook) => (
+ <RadioGroupStackedItem
+ key={webhook.value}
+ id={webhook.value}
+ value={webhook.value}
+ label=""
+ showIndicator={false}
+ >
+ <div className="flex items-center space-x-5">
+ <Image
+ alt={webhook.label}
+ src={webhook.icon}
+ layout="fixed"
+ width="32"
+ height="32"
+ />
+ <div className="flex-col space-y-0">
+ <div className="flex space-x-2">
+ <p className="text-foreground">{webhook.label}</p>
+ </div>
+ <p className="text-foreground-light">{webhook.description}</p>
+ </div>
+ </div>
+ </RadioGroupStackedItem>
+ ))}
+ </RadioGroupStacked>
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
</FormSectionContent>
</FormSection>
<SidePanel.Separator />
-
- <HTTPRequestFields
- type={values.function_type}
- errors={errors}
- httpHeaders={httpHeaders}
- httpParameters={httpParameters}
- onAddHeaders={(headers?: any[]) => {
- if (headers) setHttpHeaders(httpHeaders.concat(headers))
- else setHttpHeaders(httpHeaders.concat({ id: uuidv4(), name: '', value: '' }))
- }}
- onUpdateHeader={(idx, property, value) =>
- setHttpHeaders(
- httpHeaders.map((header, i) => {
- if (idx === i) return { ...header, [property]: value }
- else return header
- })
- )
- }
- onRemoveHeader={(idx) => setHttpHeaders(httpHeaders.filter((_, i) => idx !== i))}
- onAddParameter={() =>
- setHttpParameters(httpParameters.concat({ id: uuidv4(), name: '', value: '' }))
- }
- onUpdateParameter={(idx, property, value) =>
- setHttpParameters(
- httpParameters.map((param, i) => {
- if (idx === i) return { ...param, [property]: value }
- else return param
- })
- )
- }
- onRemoveParameter={(idx) => setHttpParameters(httpParameters.filter((_, i) => idx !== i))}
- />
-
- <button ref={submitRef} type="submit" className="hidden" />
+ <HTTPRequestConfig form={form} />
+ <SidePanel.Separator />
+ <HTTPHeaders form={form} />
+ <SidePanel.Separator />
+ <HTTPParameters form={form} />
</div>
)
}
diff --git a/apps/studio/components/interfaces/Database/Hooks/HTTPHeaders.tsx b/apps/studio/components/interfaces/Database/Hooks/HTTPHeaders.tsx
new file mode 100644
index 00000000000..de803045bbd
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/Hooks/HTTPHeaders.tsx
@@ -0,0 +1,170 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useParams } from 'common'
+import { ChevronDown, Plus, Trash } from 'lucide-react'
+import { useFieldArray, UseFormReturn } from 'react-hook-form'
+import {
+ Button,
+ cn,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ Input_Shadcn_,
+ useWatch_Shadcn_,
+} from 'ui'
+
+import { WebhookFormValues } from './EditHookPanel.constants'
+import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
+import {
+ FormSection,
+ FormSectionContent,
+ FormSectionLabel,
+} from '@/components/ui/Forms/FormSection'
+import { getKeys, useAPIKeysQuery } from '@/data/api-keys/api-keys-query'
+import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
+import { uuidv4 } from '@/lib/helpers'
+
+interface HTTPHeadersProps {
+ form: UseFormReturn<WebhookFormValues>
+}
+
+export const HTTPHeaders = ({ form }: HTTPHeadersProps) => {
+ const { ref } = useParams()
+ const { can: canReadAPIKeys } = useAsyncCheckPermissions(PermissionAction.SECRETS_READ, '*')
+
+ const { data: apiKeys } = useAPIKeysQuery(
+ { projectRef: ref, reveal: true },
+ { enabled: canReadAPIKeys }
+ )
+
+ const { serviceKey, secretKey } = getKeys(apiKeys)
+ const apiKey = secretKey?.api_key ?? serviceKey?.api_key ?? '[YOUR API KEY]'
+
+ const functionType = useWatch_Shadcn_({ control: form.control, name: 'function_type' })
+
+ const {
+ fields: headerFields,
+ append: appendHeader,
+ remove: removeHeader,
+ } = useFieldArray({
+ control: form.control,
+ name: 'httpHeaders',
+ })
+
+ const onAddHeaders = (headers?: { id: string; name: string; value: string }[]) => {
+ if (headers) {
+ headers.forEach((header) => appendHeader(header))
+ } else {
+ appendHeader({ id: uuidv4(), name: '', value: '' })
+ }
+ }
+
+ return (
+ <FormSection
+ header={<FormSectionLabel className="lg:!col-span-4">HTTP Headers</FormSectionLabel>}
+ >
+ <FormSectionContent loading={false} className="lg:!col-span-8">
+ <div className="space-y-2">
+ {headerFields.map((field, index) => (
+ <div key={field.id} className="flex items-center space-x-2">
+ <FormField_Shadcn_
+ control={form.control}
+ name={`httpHeaders.${index}.name`}
+ render={({ field }) => (
+ <FormControl_Shadcn_>
+ <Input_Shadcn_ {...field} className="w-full" placeholder="Header name" />
+ </FormControl_Shadcn_>
+ )}
+ />
+ <FormField_Shadcn_
+ control={form.control}
+ name={`httpHeaders.${index}.value`}
+ render={({ field }) => (
+ <FormControl_Shadcn_>
+ <Input_Shadcn_ {...field} className="w-full" placeholder="Header value" />
+ </FormControl_Shadcn_>
+ )}
+ />
+ <ButtonTooltip
+ type="text"
+ icon={<Trash />}
+ className="py-4"
+ onClick={() => removeHeader(index)}
+ tooltip={{ content: { side: 'bottom', text: 'Remove header' } }}
+ />
+ </div>
+ ))}
+ <div className="flex items-center">
+ <Button
+ type="default"
+ size="tiny"
+ icon={<Plus />}
+ className={cn(functionType === 'supabase_function' && 'rounded-r-none px-3')}
+ onClick={() => onAddHeaders()}
+ >
+ Add a new header
+ </Button>
+ {functionType === 'supabase_function' && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="default"
+ icon={<ChevronDown />}
+ className="rounded-l-none px-[4px] py-[5px]"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" side="bottom">
+ <DropdownMenuItem
+ key="add-auth-header"
+ onClick={() => {
+ onAddHeaders([
+ {
+ id: uuidv4(),
+ name: 'Authorization',
+ value: `Bearer ${apiKey}`,
+ },
+ ...(serviceKey?.type === 'secret'
+ ? [{ id: uuidv4(), name: 'apikey', value: apiKey }]
+ : []),
+ ])
+ }}
+ >
+ <div className="space-y-1">
+ <p className="block text-foreground">Add auth header with secret key</p>
+ <p className="text-foreground-light">
+ Required if your edge function enforces JWT verification
+ </p>
+ </div>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ key="add-source-header"
+ onClick={() =>
+ onAddHeaders([
+ {
+ id: uuidv4(),
+ name: 'x-supabase-webhook-source',
+ value: `[Use a secret value]`,
+ },
+ ])
+ }
+ >
+ <div className="space-y-1">
+ <p className="block text-foreground">Add custom source header</p>
+ <p className="text-foreground-light">
+ Useful to verify that the edge function was triggered from this webhook
+ </p>
+ </div>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+ </div>
+ </FormSectionContent>
+ </FormSection>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/Hooks/HTTPParameters.tsx b/apps/studio/components/interfaces/Database/Hooks/HTTPParameters.tsx
new file mode 100644
index 00000000000..7daeb981b66
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/Hooks/HTTPParameters.tsx
@@ -0,0 +1,77 @@
+import { Plus, Trash } from 'lucide-react'
+import { useFieldArray, UseFormReturn } from 'react-hook-form'
+import { Button, FormControl_Shadcn_, FormField_Shadcn_, Input_Shadcn_, SidePanel } from 'ui'
+
+import { WebhookFormValues } from './EditHookPanel.constants'
+import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
+import {
+ FormSection,
+ FormSectionContent,
+ FormSectionLabel,
+} from '@/components/ui/Forms/FormSection'
+import { uuidv4 } from '@/lib/helpers'
+
+interface HTTPParametersProps {
+ form: UseFormReturn<WebhookFormValues>
+}
+
+export const HTTPParameters = ({ form }: HTTPParametersProps) => {
+ const {
+ fields: paramFields,
+ append: appendParam,
+ remove: removeParam,
+ } = useFieldArray({
+ control: form.control,
+ name: 'httpParameters',
+ })
+
+ return (
+ <FormSection
+ header={<FormSectionLabel className="lg:!col-span-4">HTTP Parameters</FormSectionLabel>}
+ >
+ <FormSectionContent loading={false} className="lg:!col-span-8">
+ <div className="space-y-2">
+ {paramFields.map((field, index) => (
+ <div key={field.id} className="flex items-center space-x-2">
+ <FormField_Shadcn_
+ control={form.control}
+ name={`httpParameters.${index}.name`}
+ render={({ field }) => (
+ <FormControl_Shadcn_>
+ <Input_Shadcn_ {...field} className="w-full" placeholder="Parameter name" />
+ </FormControl_Shadcn_>
+ )}
+ />
+ <FormField_Shadcn_
+ control={form.control}
+ name={`httpParameters.${index}.value`}
+ render={({ field }) => (
+ <FormControl_Shadcn_>
+ <Input_Shadcn_ {...field} className="w-full" placeholder="Parameter value" />
+ </FormControl_Shadcn_>
+ )}
+ />
+ <ButtonTooltip
+ type="text"
+ className="py-4"
+ icon={<Trash />}
+ onClick={() => removeParam(index)}
+ tooltip={{ content: { side: 'bottom', text: 'Remove parameter' } }}
+ />
+ </div>
+ ))}
+ <div>
+ <Button
+ type="default"
+ size="tiny"
+ icon={<Plus />}
+ onClick={() => appendParam({ id: uuidv4(), name: '', value: '' })}
+ >
+ Add a new parameter
+ </Button>
+ </div>
+ </div>
+ </FormSectionContent>
+ </FormSection>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/Hooks/HTTPRequestConfig.tsx b/apps/studio/components/interfaces/Database/Hooks/HTTPRequestConfig.tsx
new file mode 100644
index 00000000000..5d546bb46bb
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/Hooks/HTTPRequestConfig.tsx
@@ -0,0 +1,164 @@
+import { useParams } from 'common'
+import Link from 'next/link'
+import { UseFormReturn } from 'react-hook-form'
+import {
+ Button,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ Input_Shadcn_,
+ Select_Shadcn_,
+ SelectContent_Shadcn_,
+ SelectItem_Shadcn_,
+ SelectTrigger_Shadcn_,
+ SelectValue_Shadcn_,
+ useWatch_Shadcn_,
+} from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+
+import { WebhookFormValues } from './EditHookPanel.constants'
+import {
+ FormSection,
+ FormSectionContent,
+ FormSectionLabel,
+} from '@/components/ui/Forms/FormSection'
+import { useEdgeFunctionsQuery } from '@/data/edge-functions/edge-functions-query'
+import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
+
+interface HTTPRequestConfigProps {
+ form: UseFormReturn<WebhookFormValues>
+}
+
+export const HTTPRequestConfig = ({ form }: HTTPRequestConfigProps) => {
+ const { ref } = useParams()
+ const { data: selectedProject } = useSelectedProjectQuery()
+
+ const { data: functions } = useEdgeFunctionsQuery({ projectRef: ref })
+
+ const edgeFunctions = functions ?? []
+ const functionType = useWatch_Shadcn_({ control: form.control, name: 'function_type' })
+
+ return (
+ <FormSection
+ header={
+ <FormSectionLabel className="lg:!col-span-4">
+ {functionType === 'http_request'
+ ? 'HTTP Request'
+ : functionType === 'supabase_function'
+ ? 'Edge Function'
+ : ''}
+ </FormSectionLabel>
+ }
+ >
+ <FormSectionContent loading={false} className="lg:!col-span-8">
+ <FormField_Shadcn_
+ control={form.control}
+ name="http_method"
+ render={({ field }) => (
+ <FormItemLayout label="Method" layout="vertical" className="gap-1">
+ <Select_Shadcn_ value={field.value} onValueChange={field.onChange}>
+ <FormControl_Shadcn_>
+ <SelectTrigger_Shadcn_>
+ <SelectValue_Shadcn_ />
+ </SelectTrigger_Shadcn_>
+ </FormControl_Shadcn_>
+ <SelectContent_Shadcn_>
+ <SelectItem_Shadcn_ value="GET">GET</SelectItem_Shadcn_>
+ <SelectItem_Shadcn_ value="POST">POST</SelectItem_Shadcn_>
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+
+ {functionType === 'http_request' ? (
+ <FormField_Shadcn_
+ control={form.control}
+ name="http_url"
+ render={({ field }) => (
+ <FormItemLayout
+ label="URL"
+ layout="vertical"
+ className="gap-1"
+ description="URL of the HTTP request. Must include HTTP/HTTPS"
+ >
+ <FormControl_Shadcn_>
+ <Input_Shadcn_ {...field} placeholder="http://api.com/path/resource" />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ ) : functionType === 'supabase_function' && edgeFunctions.length === 0 ? (
+ <div className="space-y-1">
+ <p className="text-sm text-foreground-light">Select which edge function to trigger</p>
+ <div className="px-4 py-4 border rounded bg-surface-300 border-strong flex items-center justify-between space-x-4">
+ <p className="text-sm">No edge functions created yet</p>
+ <Button asChild>
+ <Link href={`/project/${ref}/functions`}>Create an edge function</Link>
+ </Button>
+ </div>
+ </div>
+ ) : functionType === 'supabase_function' && edgeFunctions.length > 0 ? (
+ <FormField_Shadcn_
+ control={form.control}
+ name="http_url"
+ render={({ field }) => (
+ <FormItemLayout
+ label="Select which edge function to trigger"
+ layout="vertical"
+ className="gap-1"
+ >
+ <Select_Shadcn_ value={field.value} onValueChange={field.onChange}>
+ <FormControl_Shadcn_>
+ <SelectTrigger_Shadcn_>
+ <SelectValue_Shadcn_ placeholder="Select an edge function" />
+ </SelectTrigger_Shadcn_>
+ </FormControl_Shadcn_>
+ <SelectContent_Shadcn_>
+ {edgeFunctions.map((fn) => {
+ const restUrl = selectedProject?.restUrl
+ const restUrlTld = restUrl ? new URL(restUrl).hostname.split('.').pop() : 'co'
+ const functionUrl = `https://${ref}.supabase.${restUrlTld}/functions/v1/${fn.slug}`
+
+ return (
+ <SelectItem_Shadcn_ key={fn.id} value={functionUrl}>
+ {fn.name}
+ </SelectItem_Shadcn_>
+ )
+ })}
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ ) : null}
+
+ <FormField_Shadcn_
+ control={form.control}
+ name="timeout_ms"
+ render={({ field }) => (
+ <FormItemLayout
+ label="Timeout"
+ labelOptional="Between 1000ms to 10,000ms"
+ layout="vertical"
+ className="gap-1"
+ >
+ <FormControl_Shadcn_>
+ <div className="relative">
+ <Input_Shadcn_
+ {...field}
+ type="number"
+ onChange={(e) => field.onChange(Number(e.target.value))}
+ className="pr-10"
+ />
+ <span className="absolute right-3 top-1/2 -translate-y-1/2 text-foreground-light text-sm">
+ ms
+ </span>
+ </div>
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ </FormSectionContent>
+ </FormSection>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx b/apps/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx
deleted file mode 100644
index b27d8a35296..00000000000
--- a/apps/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx
+++ /dev/null
@@ -1,275 +0,0 @@
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { ChevronDown, Plus, X } from 'lucide-react'
-import Link from 'next/link'
-
-import { useParams } from 'common'
-import { ButtonTooltip } from 'components/ui/ButtonTooltip'
-import { FormSection, FormSectionContent, FormSectionLabel } from 'components/ui/Forms/FormSection'
-import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
-import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'
-import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
-import { uuidv4 } from 'lib/helpers'
-import {
- Button,
- cn,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
- Input,
- Listbox,
- SidePanel,
-} from 'ui'
-import { HTTPArgument } from './EditHookPanel'
-
-interface HTTPRequestFieldsProps {
- type: 'http_request' | 'supabase_function'
- errors: any
- httpHeaders: HTTPArgument[]
- httpParameters: HTTPArgument[]
- onAddHeaders: (headers?: any[]) => void
- onUpdateHeader: (idx: number, property: string, value: string) => void
- onRemoveHeader: (idx: number) => void
- onAddParameter: () => void
- onUpdateParameter: (idx: number, property: string, value: string) => void
- onRemoveParameter: (idx: number) => void
-}
-
-const HTTPRequestFields = ({
- type,
- errors,
- httpHeaders = [],
- httpParameters = [],
- onAddHeaders,
- onUpdateHeader,
- onRemoveHeader,
- onAddParameter,
- onUpdateParameter,
- onRemoveParameter,
-}: HTTPRequestFieldsProps) => {
- const { ref } = useParams()
- const { data: selectedProject } = useSelectedProjectQuery()
- const { can: canReadAPIKeys } = useAsyncCheckPermissions(PermissionAction.SECRETS_READ, '*')
-
- const { data: functions } = useEdgeFunctionsQuery({ projectRef: ref })
- const { data: apiKeys } = useAPIKeysQuery(
- { projectRef: ref, reveal: true },
- { enabled: canReadAPIKeys }
- )
-
- const edgeFunctions = functions ?? []
- const { serviceKey, secretKey } = getKeys(apiKeys)
- const apiKey = secretKey?.api_key ?? serviceKey?.api_key ?? '[YOUR API KEY]'
-
- return (
- <>
- <FormSection
- header={
- <FormSectionLabel className="lg:!col-span-4">
- {type === 'http_request'
- ? 'HTTP Request'
- : type === 'supabase_function'
- ? 'Edge Function'
- : ''}
- </FormSectionLabel>
- }
- >
- <FormSectionContent loading={false} className="lg:!col-span-8">
- <Listbox id="http_method" name="http_method" size="medium" label="Method">
- <Listbox.Option id="GET" value="GET" label="GET">
- GET
- </Listbox.Option>
- <Listbox.Option id="POST" value="POST" label="POST">
- POST
- </Listbox.Option>
- </Listbox>
- {type === 'http_request' ? (
- <Input
- id="http_url"
- name="http_url"
- label="URL"
- placeholder="http://api.com/path/resource"
- descriptionText="URL of the HTTP request. Must include HTTP/HTTPS"
- />
- ) : type === 'supabase_function' && edgeFunctions.length === 0 ? (
- <div className="space-y-1">
- <p className="text-sm text-foreground-light">Select which edge function to trigger</p>
- <div className="px-4 py-4 border rounded bg-surface-300 border-strong flex items-center justify-between space-x-4">
- <p className="text-sm">No edge functions created yet</p>
- <Button asChild>
- <Link href={`/project/${ref}/functions`}>Create an edge function</Link>
- </Button>
- </div>
- {errors.http_url && <p className="text-sm text-red-900">{errors.http_url}</p>}
- </div>
- ) : type === 'supabase_function' && edgeFunctions.length > 0 ? (
- <Listbox id="http_url" name="http_url" label="Select which edge function to trigger">
- {edgeFunctions.map((fn) => {
- const restUrl = selectedProject?.restUrl
- const restUrlTld = restUrl ? new URL(restUrl).hostname.split('.').pop() : 'co'
- const functionUrl = `https://${ref}.supabase.${restUrlTld}/functions/v1/${fn.slug}`
-
- return (
- <Listbox.Option key={fn.id} id={functionUrl} value={functionUrl} label={fn.name}>
- {fn.name}
- </Listbox.Option>
- )
- })}
- </Listbox>
- ) : null}
- <Input
- id="timeout_ms"
- name="timeout_ms"
- label="Timeout"
- labelOptional="Between 1000ms to 10,000ms"
- type="number"
- actions={<p className="text-foreground-light pr-2">ms</p>}
- />
- </FormSectionContent>
- </FormSection>
- <SidePanel.Separator />
- <FormSection
- header={<FormSectionLabel className="lg:!col-span-4">HTTP Headers</FormSectionLabel>}
- >
- <FormSectionContent loading={false} className="lg:!col-span-8">
- <div className="space-y-2">
- {httpHeaders.map((header, idx: number) => (
- <div key={header.id} className="flex items-center space-x-2">
- <Input
- value={header.name}
- size="small"
- className="w-full"
- placeholder="Header name"
- onChange={(event: any) => onUpdateHeader(idx, 'name', event.target.value)}
- />
- <Input
- value={header.value}
- size="small"
- className="w-full"
- placeholder="Header value"
- onChange={(event: any) => onUpdateHeader(idx, 'value', event.target.value)}
- />
- <ButtonTooltip
- type="text"
- icon={<X />}
- className="py-4"
- onClick={() => onRemoveHeader(idx)}
- tooltip={{ content: { side: 'bottom', text: 'Remove header' } }}
- />
- </div>
- ))}
- <div className="flex items-center">
- <Button
- type="default"
- size="tiny"
- icon={<Plus />}
- className={cn(type === 'supabase_function' && 'rounded-r-none px-3')}
- onClick={() => onAddHeaders()}
- >
- Add a new header
- </Button>
- {type === 'supabase_function' && (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- type="default"
- icon={<ChevronDown />}
- className="rounded-l-none px-[4px] py-[5px]"
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" side="bottom">
- <DropdownMenuItem
- key="add-auth-header"
- onClick={() => {
- onAddHeaders([
- {
- id: uuidv4(),
- name: 'Authorization',
- value: `Bearer ${apiKey}`,
- },
- ...(serviceKey?.type === 'secret'
- ? [{ id: uuidv4(), name: 'apikey', value: apiKey }]
- : []),
- ])
- }}
- >
- <div className="space-y-1">
- <p className="block text-foreground">Add auth header with secret key</p>
- <p className="text-foreground-light">
- Required if your edge function enforces JWT verification
- </p>
- </div>
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- key="add-source-header"
- onClick={() =>
- onAddHeaders([
- {
- id: uuidv4(),
- name: 'x-supabase-webhook-source',
- value: `[Use a secret value]`,
- },
- ])
- }
- >
- <div className="space-y-1">
- <p className="block text-foreground">Add custom source header</p>
- <p className="text-foreground-light">
- Useful to verify that the edge function was triggered from this webhook
- </p>
- </div>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- )}
- </div>
- </div>
- </FormSectionContent>
- </FormSection>
- <SidePanel.Separator />
- <FormSection
- header={<FormSectionLabel className="lg:!col-span-4">HTTP Parameters</FormSectionLabel>}
- >
- <FormSectionContent loading={false} className="lg:!col-span-8">
- <div className="space-y-2">
- {httpParameters.map((parameter, idx: number) => (
- <div key={parameter.id} className="flex items-center space-x-2">
- <Input
- size="small"
- value={parameter.name}
- className="w-full"
- placeholder="Parameter name"
- onChange={(event: any) => onUpdateParameter(idx, 'name', event.target.value)}
- />
- <Input
- size="small"
- value={parameter.value}
- className="w-full"
- placeholder="Parameter value"
- onChange={(event: any) => onUpdateParameter(idx, 'value', event.target.value)}
- />
- <ButtonTooltip
- type="text"
- className="py-4"
- icon={<X />}
- onClick={() => onRemoveParameter(idx)}
- tooltip={{ content: { side: 'bottom', text: 'Remove parameter' } }}
- />
- </div>
- ))}
- <div>
- <Button type="default" size="tiny" icon={<Plus />} onClick={onAddParameter}>
- Add a new parameter
- </Button>
- </div>
- </div>
- </FormSectionContent>
- </FormSection>
- </>
- )
-}
-
-export default HTTPRequestFields
diff --git a/apps/studio/components/interfaces/Integrations/Webhooks/ListTab.tsx b/apps/studio/components/interfaces/Integrations/Webhooks/ListTab.tsx
index 46ce4496507..9c74948e713 100644
--- a/apps/studio/components/interfaces/Integrations/Webhooks/ListTab.tsx
+++ b/apps/studio/components/interfaces/Integrations/Webhooks/ListTab.tsx
@@ -1,17 +1,16 @@
import { PostgresTrigger } from '@supabase/postgres-meta'
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { parseAsBoolean, useQueryState } from 'nuqs'
-import { useRef } from 'react'
-import { toast } from 'sonner'
+import { parseAsBoolean, parseAsString, useQueryState } from 'nuqs'
+import { useMemo, useRef } from 'react'
-import DeleteHookModal from 'components/interfaces/Database/Hooks/DeleteHookModal'
-import { EditHookPanel } from 'components/interfaces/Database/Hooks/EditHookPanel'
-import { HooksList } from 'components/interfaces/Database/Hooks/HooksList/HooksList'
-import NoPermission from 'components/ui/NoPermission'
-import { useDatabaseHooksQuery } from 'data/database-triggers/database-triggers-query'
-import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { handleErrorOnDelete, useQueryStateWithSelect } from 'hooks/misc/useQueryStateWithSelect'
-import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
+import DeleteHookModal from '@/components/interfaces/Database/Hooks/DeleteHookModal'
+import { EditHookPanel } from '@/components/interfaces/Database/Hooks/EditHookPanel'
+import { HooksList } from '@/components/interfaces/Database/Hooks/HooksList/HooksList'
+import NoPermission from '@/components/ui/NoPermission'
+import { useDatabaseHooksQuery } from '@/data/database-triggers/database-triggers-query'
+import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
+import { handleErrorOnDelete, useQueryStateWithSelect } from '@/hooks/misc/useQueryStateWithSelect'
+import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
export const WebhooksListTab = () => {
const { data: project } = useSelectedProjectQuery()
@@ -24,6 +23,11 @@ export const WebhooksListTab = () => {
parseAsBoolean.withDefault(false).withOptions({ history: 'push', clearOnDefault: true })
)
+ const [selectedHookIdToEdit, setSelectedHookIdToEdit] = useQueryState(
+ 'edit',
+ parseAsString.withDefault('').withOptions({ history: 'push', clearOnDefault: true })
+ )
+
const { can: canReadWebhooks, isSuccess: isPermissionsLoaded } = useAsyncCheckPermissions(
PermissionAction.TENANT_SQL_ADMIN_READ,
'triggers'
@@ -34,13 +38,6 @@ export const WebhooksListTab = () => {
connectionString: project?.connectionString,
})
- const { setValue: setSelectedHookToEdit, value: selectedHookToEdit } = useQueryStateWithSelect({
- urlKey: 'edit',
- select: (id: string) => (id ? hooks?.find((hook) => hook.id.toString() === id) : undefined),
- enabled: !!hooks && !isLoadingHooks,
- onError: () => toast.error(`Webhook not found`),
- })
-
const { setValue: setSelectedHookToDelete, value: selectedHookToDelete } =
useQueryStateWithSelect({
urlKey: 'delete',
@@ -55,13 +52,18 @@ export const WebhooksListTab = () => {
}
const editHook = (hook: PostgresTrigger) => {
- setSelectedHookToEdit(hook.id.toString())
+ setSelectedHookIdToEdit(hook.id.toString())
}
const deleteHook = (hook: PostgresTrigger) => {
setSelectedHookToDelete(hook.id.toString())
}
+ const selectedHookToEdit = useMemo(
+ () => hooks?.find((hook) => hook.id.toString() === selectedHookIdToEdit),
+ [hooks, selectedHookIdToEdit]
+ )
+
if (isPermissionsLoaded && !canReadWebhooks) {
return <NoPermission isFullPage resourceText="view database webhooks" />
}
@@ -75,7 +77,7 @@ export const WebhooksListTab = () => {
selectedHook={selectedHookToEdit}
onClose={() => {
setShowCreateHookForm(false)
- setSelectedHookToEdit(null)
+ setSelectedHookIdToEdit('')
}}
/>
<DeleteHookModal
diff --git a/apps/studio/data/table-editor/table-editor-query.ts b/apps/studio/data/table-editor/table-editor-query.ts
index 354456a1dbb..a955e1010f0 100644
--- a/apps/studio/data/table-editor/table-editor-query.ts
+++ b/apps/studio/data/table-editor/table-editor-query.ts
@@ -1,10 +1,11 @@
-import { QueryClient, useQuery } from '@tanstack/react-query'
+import { QueryClient, queryOptions, useQuery } from '@tanstack/react-query'
+import { id } from 'common-tags'
+import { UseCustomQueryOptions } from 'types'
import { executeSql, ExecuteSqlError } from '../sql/execute-sql-query'
import { tableEditorKeys } from './keys'
import { getTableEditorSql } from './table-editor-query-sql'
import { Entity } from './table-editor-types'
-import { UseCustomQueryOptions } from 'types'
type TableEditorArgs = {
id?: number
@@ -48,8 +49,7 @@ export const useTableEditorQuery = <TData = TableEditorData>(
}: UseCustomQueryOptions<TableEditorData, TableEditorError, TData> = {}
) =>
useQuery<TableEditorData, TableEditorError, TData>({
- queryKey: tableEditorKeys.tableEditor(projectRef, id),
- queryFn: ({ signal }) => getTableEditor({ projectRef, connectionString, id }, signal),
+ ...tableEditorQueryOptions({ projectRef, connectionString, id }),
enabled:
enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined' && !isNaN(id),
refetchOnWindowFocus: false,
@@ -62,16 +62,16 @@ export function prefetchTableEditor(
client: QueryClient,
{ projectRef, connectionString, id }: TableEditorVariables
) {
- return client.fetchQuery({
+ return client.fetchQuery(tableEditorQueryOptions({ projectRef, connectionString, id }))
+}
+
+export const tableEditorQueryOptions = <TData = TableEditorData>({
+ projectRef,
+ connectionString,
+ id,
+}: TableEditorVariables) => {
+ return queryOptions<TableEditorData, TableEditorError, TData>({
queryKey: tableEditorKeys.tableEditor(projectRef, id),
- queryFn: ({ signal }) =>
- getTableEditor(
- {
- projectRef,
- connectionString,
- id,
- },
- signal
- ),
+ queryFn: ({ signal }) => getTableEditor({ projectRef, connectionString, id }, signal),
})
}