The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Add support for Supabase Edge Functions
Joshen Lim4cafd1968a4f
diff --git a/packages/ui/src/components/Listbox/Listbox2.tsx b/packages/ui/src/components/Listbox/Listbox2.tsxindex 2049efdf007..288c3e4c0d3 100644--- a/packages/ui/src/components/Listbox/Listbox2.tsx+++ b/packages/ui/src/components/Listbox/Listbox2.tsx@@ -76,6 +76,7 @@ function Listbox({useFormContext()if (values && !value) {+ value = values[id || name]defaultValue = values[id || name]}diff --git a/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx b/studio/components/interfaces/Database/Hooks/EditHookPanel.tsxindex 583ab66294b..c8a0fe78e38 100644--- a/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx+++ b/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx@@ -3,16 +3,18 @@ import { useState, useRef, useEffect } from 'react'import { PostgresTrigger } from '@supabase/postgres-meta'import { Button, SidePanel, Form, Input, Listbox, Checkbox, Radio, Badge, Modal } from 'ui'-import { useStore } from 'hooks'+import { useParams, useStore } from 'hooks'import { tryParseJson, uuidv4 } from 'lib/helpers'import HTTPRequestFields from './HTTPRequestFields'import { isValidHttpUrl } from './Hooks.utils'import { AVAILABLE_WEBHOOK_TYPES, HOOK_EVENTS } from './Hooks.constants'+import ConfirmationModal from 'components/ui/ConfirmationModal'import { FormSection, FormSectionLabel, FormSectionContent } from 'components/ui/Forms'import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'++import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'import { useDatabaseTriggerCreateMutation } from 'data/database-triggers/database-trigger-create-mutation'import { useDatabaseTriggerUpdateMutation } from 'data/database-triggers/database-trigger-update-transaction-mutation'-import ConfirmationModal from 'components/ui/ConfirmationModal'export interface EditHookPanelProps {visible: boolean@@ -24,6 +26,7 @@ export type HTTPArgument = { id: string; name: string; value: string }const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) => {// [Joshen] Need to change to use RQ once Alaister's PR goes in+ const { ref } = useParams()const { meta, ui } = useStore()const submitRef: any = useRef()const [isEdited, setIsEdited] = useState(false)@@ -40,16 +43,25 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =const [httpParameters, setHttpParameters] = useState<HTTPArgument[]>([])const { project } = useProjectContext()+ const { data: functions } = useEdgeFunctionsQuery({ projectRef: ref })const { mutateAsync: createDatabaseTrigger } = useDatabaseTriggerCreateMutation()const { mutateAsync: updateDatabaseTrigger } = useDatabaseTriggerUpdateMutation()- const tables = meta.tables.list()+ const tables = meta.tables.list().sort((a, b) => (a.schema > b.schema ? 0 : -1))+ const restUrl = ui.selectedProject?.restUrl+ const restUrlTld = new URL(restUrl as string).hostname.split('.').pop()++ const isEdgeFunction = (url: string) =>+ url.includes(`https://${ref}.functions.supabase.${restUrlTld}/`)+const initialValues = {name: selectedHook?.name ?? '',table_id: selectedHook?.table_id ?? '',- function_name: selectedHook?.function_name ?? 'http_request',http_url: selectedHook?.function_args?.[0] ?? '',http_method: selectedHook?.function_args?.[1] ?? 'GET',+ function_type: isEdgeFunction(selectedHook?.function_args?.[0] ?? '')+ ? 'supabase_function'+ : 'http_request',}useEffect(() => {@@ -107,7 +119,7 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =errors['table_id'] = 'Please select a table for which your webhook will trigger from'}- if (values.function_name === 'http_request') {+ if (values.function_type === 'http_request') {// For HTTP requestsif (!values.http_url) {errors['http_url'] = 'Please provide a URL'@@ -116,7 +128,7 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =} else if (!isValidHttpUrl(values.http_url)) {errors['http_url'] = 'Please provide a valid URL'}- } else if (values.function_name === 'supabase_function') {+ } else if (values.function_type === 'supabase_function') {// For Supabase Edge Functions}@@ -137,6 +149,20 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =return ui.setNotification({ category: 'error', message: 'Unable to find selected table' })}+ const serviceTimeoutMs = '1000'+ 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+ }, {})+const payload: any = {events,activation: 'AFTER',@@ -146,34 +172,15 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =table: selectedTable.name,schema: selectedTable.schema,table_id: values.table_id,- function_name: values.function_name,+ function_name: 'http_request',function_schema: 'supabase_functions',- function_args: [],- }-- if (values.function_name === 'http_request') {- const serviceTimeoutMs = '1000'- 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- }, {})- payload.function_args = [+ function_args: [values.http_url,values.http_method,JSON.stringify(headers),JSON.stringify(parameters),serviceTimeoutMs,- ]- } else if (values.function_name === 'supabase_function') {- payload.function_args = []+ ],}if (selectedHook === undefined) {@@ -266,7 +273,28 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =}><Form validateOnBlur initialValues={initialValues} onSubmit={onSubmit} validate={validate}>- {() => {+ {({ values, resetForm }: any) => {+ 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') {+ const fnSlug = (functions ?? [])[0]?.slug+ const defaultFunctionUrl = `https://${ref}.functions.supabase.${restUrlTld}/${fnSlug}`+ const updatedValues = {+ ...values,+ http_url: isEdgeFunction(values.http_url) ? values.http_url : defaultFunctionUrl,+ }+ resetForm({ values: updatedValues, initialValues: updatedValues })+ }+ }, [values.function_type])+return (<div><FormSection@@ -320,8 +348,8 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =label={table.name}><div className="flex items-center space-x-2">- <p>{table.name}</p>- <p className="text-scale-1100">{table.schema}</p>+ <p className="text-scale-1000">{table.schema}</p>+ <p className="text-scale-1200">{table.name}</p></div></Listbox.Option>))}@@ -356,8 +384,8 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =><FormSectionContent loading={false} className="lg:!col-span-8"><Radio.Group- id="function_name"- name="function_name"+ id="function_type"+ name="function_type"label="Type of hook"type="cards">@@ -392,11 +420,13 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =<SidePanel.Separator /><HTTPRequestFields+ type={values.function_type}httpHeaders={httpHeaders}httpParameters={httpParameters}- onAddHeader={() =>- setHttpHeaders(httpHeaders.concat({ id: uuidv4(), name: '', value: '' }))- }+ onAddHeader={(header?: any) => {+ if (header) setHttpHeaders(httpHeaders.concat(header))+ else setHttpHeaders(httpHeaders.concat({ id: uuidv4(), name: '', value: '' }))+ }}onUpdateHeader={(idx, property, value) =>setHttpHeaders(httpHeaders.map((header, i) => {diff --git a/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx b/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsxindex 8f5c9a241c5..51ed49ab03f 100644--- a/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx+++ b/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx@@ -1,11 +1,26 @@-import { Button, Listbox, Input, SidePanel, IconTrash, IconPlus } from 'ui'+import {+ Button,+ Listbox,+ Input,+ SidePanel,+ IconTrash,+ IconPlus,+ Dropdown,+ IconChevronDown,+} from 'ui'import { FormSection, FormSectionLabel, FormSectionContent } from 'components/ui/Forms'import { HTTPArgument } from './EditHookPanel'+import { useParams, useStore } from 'hooks'+import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'+import clsx from 'clsx'+import { uuidv4 } from 'lib/helpers'+import { useProjectApiQuery } from 'data/config/project-api-query'interface HTTPRequestFieldsProps {+ type: 'http_request' | 'supabase_function'httpHeaders: HTTPArgument[]httpParameters: HTTPArgument[]- onAddHeader: () => void+ onAddHeader: (header?: any) => voidonUpdateHeader: (idx: number, property: string, value: string) => voidonRemoveHeader: (idx: number) => voidonAddParameter: () => void@@ -14,6 +29,7 @@ interface HTTPRequestFieldsProps {}const HTTPRequestFields = ({+ type,httpHeaders = [],httpParameters = [],onAddHeader,@@ -23,10 +39,28 @@ const HTTPRequestFields = ({onUpdateParameter,onRemoveParameter,}: HTTPRequestFieldsProps) => {+ const { ui } = useStore()+ const { ref } = useParams()+ const { data: settings } = useProjectApiQuery({ projectRef: ref })+ const { data: functions } = useEdgeFunctionsQuery({ projectRef: ref })++ const apiService = settings?.autoApiService+ const anonKey = apiService?.service_api_keys.find((x) => x.name === 'anon key')+ ? apiService.defaultApiKey+ : '[YOUR ANON KEY]'+return (<><FormSection- header={<FormSectionLabel className="lg:!col-span-4">HTTP Request</FormSectionLabel>}+ 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">@@ -37,13 +71,29 @@ const HTTPRequestFields = ({POST</Listbox.Option></Listbox>- <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 === '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' ? (+ <Listbox id="http_url" name="http_url" label="Select which edge function to trigger">+ {(functions ?? []).map((fn) => {+ const restUrl = ui.selectedProject?.restUrl+ const restUrlTld = new URL(restUrl as string).hostname.split('.').pop()+ const functionUrl = `https://${ref}.functions.supabase.${restUrlTld}/${fn.slug}`++ return (+ <Listbox.Option key={fn.id} id={functionUrl} value={functionUrl} label={fn.name}>+ {fn.name}+ </Listbox.Option>+ )+ })}+ </Listbox>+ ) : null}</FormSectionContent></FormSection><SidePanel.Separator />@@ -77,10 +127,46 @@ const HTTPRequestFields = ({/></div>))}- <div>- <Button type="dashed" size="tiny" icon={<IconPlus />} onClick={onAddHeader}>+ <div className="flex items-center">+ <Button+ type="default"+ size="tiny"+ icon={<IconPlus />}+ className={clsx(type === 'supabase_function' && 'rounded-r-none px-3')}+ onClick={onAddHeader}+ >Add a new header</Button>+ {type === 'supabase_function' && (+ <Dropdown+ align="end"+ side="bottom"+ overlay={[+ <Dropdown.Item+ key="experimental-token"+ onClick={() =>+ onAddHeader({+ id: uuidv4(),+ name: ' Authorization',+ value: `Bearer ${anonKey}`,+ })+ }+ >+ <div className="space-y-1">+ <p className="block text-scale-1200">+ Add Authorization header with anon key+ </p>+ </div>+ </Dropdown.Item>,+ ]}+ >+ <Button+ type="default"+ className="rounded-l-none px-[4px] py-[5px]"+ icon={<IconChevronDown />}+ />+ </Dropdown>+ )}</div></div></FormSectionContent>diff --git a/studio/components/interfaces/Database/Hooks/Hooks.constants.ts b/studio/components/interfaces/Database/Hooks/Hooks.constants.tsindex 5e7287a0874..2f6a22986be 100644--- a/studio/components/interfaces/Database/Hooks/Hooks.constants.ts+++ b/studio/components/interfaces/Database/Hooks/Hooks.constants.ts@@ -42,7 +42,7 @@ export const AVAILABLE_WEBHOOK_TYPES = [description: 'Send an HTTP request to any URL.',},{- disabled: true,+ disabled: false,value: 'supabase_function',icon: `${BASE_PATH}/img/function-providers/supabase-severless-function.png`,label: 'Supabase Edge Functions',