The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Hook up PATCH, and allow users to update function name and jwt verification enforcement
Joshen Lim52bf4cff5b59
diff --git a/packages/ui/src/components/Toggle/Toggle.tsx b/packages/ui/src/components/Toggle/Toggle.tsxindex 07f4654a7ff..c22fa3d96aa 100644--- a/packages/ui/src/components/Toggle/Toggle.tsx+++ b/packages/ui/src/components/Toggle/Toggle.tsx@@ -129,7 +129,7 @@ function Toggle({type="button"id={id}name={name}- className={toggleClasses.join(' ')}+ className={`${toggleClasses.join(' ')} ${disabled ? 'opacity-50 cursor-default' : ''}`}onClick={onClick}disabled={disabled}onBlur={handleBlurEvent}diff --git a/studio/components/interfaces/Functions/EdgeFunctionDetails.tsx b/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsxsimilarity index 66%rename from studio/components/interfaces/Functions/EdgeFunctionDetails.tsxrename to studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsxindex d72d91602a2..2dd95906358 100644--- a/studio/components/interfaces/Functions/EdgeFunctionDetails.tsx+++ b/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx@@ -1,4 +1,5 @@import dayjs from 'dayjs'+import Link from 'next/link'import { useRouter } from 'next/router'import { FC, useState, useEffect } from 'react'import * as Tooltip from '@radix-ui/react-tooltip'@@ -18,8 +19,11 @@ import {import { useStore, useParams, checkPermissions } from 'hooks'import Panel from 'components/ui/Panel'-import CommandRender from './CommandRender'+import CommandRender from '../CommandRender'+import { generateCLICommands } from './EdgeFunctionDetails.utils'import { useProjectApiQuery } from 'data/config/project-api-query'+import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'+import { useEdgeFunctionUpdateMutation } from 'data/edge-functions/edge-functions-update-mutation'import { useEdgeFunctionDeleteMutation } from 'data/edge-functions/edge-functions-delete-mutation'import {FormHeader,@@ -29,29 +33,28 @@ import {FormSectionLabel,FormSectionContent,} from 'components/ui/Forms'-import Link from 'next/link'interface Props {}-// [Joshen] Next - additional configs: Verify jwt + import maps-const EdgeFunctionDetails: FC<Props> = () => {const router = useRouter()- const { functions, ui } = useStore()+ const { ui } = useStore()const { ref: projectRef, id } = useParams()const [showDeleteModal, setShowDeleteModal] = useState(false)const [showInstructions, setShowInstructions] = useState(false)const [selectedFunction, setSelectedFunction] = useState<any>(null)- const { data: settings } = useProjectApiQuery({ projectRef })+ const { data: settings, isLoading } = useProjectApiQuery({ projectRef })+ const { data: functions } = useEdgeFunctionsQuery({ projectRef })+ const { mutateAsync: updateEdgeFunction } = useEdgeFunctionUpdateMutation()const { mutateAsync: deleteEdgeFunction, isLoading: isDeleting } = useEdgeFunctionDeleteMutation()const formId = 'edge-function-update-form'const canUpdateEdgeFunction = checkPermissions(PermissionAction.FUNCTIONS_WRITE, '*')useEffect(() => {- setSelectedFunction(functions.byId(id))- }, [functions.isLoaded, ui.selectedProject])+ if (!isLoading) setSelectedFunction((functions ?? []).find((fn: any) => fn.id === id))+ }, [isLoading, ui.selectedProject])// Get the API serviceconst apiService = settings?.autoApiService@@ -68,6 +71,34 @@ const EdgeFunctionDetails: FC<Props> = () => {].join('.')const functionUrl = `${apiService?.protocol}://${functionsEndpoint}/${selectedFunction?.slug}`+ const { managementCommands, secretCommands, invokeCommands } = generateCLICommands(+ selectedFunction,+ functionUrl,+ anonKey+ )++ const onUpdateFunction = async (values: any, { setSubmitting, resetForm }: any) => {+ if (!projectRef) return console.error('Project ref is required')+ setSubmitting(true)++ try {+ await updateEdgeFunction({+ projectRef,+ slug: selectedFunction.slug,+ payload: values,+ })+ resetForm({ values, initialValues: values })+ ui.setNotification({ category: 'success', message: `Successfully updated edge function` })+ } catch (error: any) {+ ui.setNotification({+ category: 'error',+ message: `Failed to update edge function: ${error.message}`,+ })+ } finally {+ setSubmitting(false)+ }+ }+const onConfirmDelete = async () => {if (!projectRef) return console.error('Project ref is required')if (selectedFunction === undefined) return console.error('No edge function selected')@@ -87,97 +118,10 @@ const EdgeFunctionDetails: FC<Props> = () => {}}- const managementCommands: any = [- {- command: `supabase functions deploy ${selectedFunction?.slug}`,- description: 'This will overwrite the deployed function with your new function',- jsx: () => {- return (- <>- <span className="text-brand-1100">supabase</span> functions deploy{' '}- {selectedFunction?.slug}- </>- )- },- comment: 'Deploy a new version',- },- {- command: `supabase functions delete ${selectedFunction?.slug}`,- description: 'This will remove the function and all the logs associated with it',- jsx: () => {- return (- <>- <span className="text-brand-1100">supabase</span> functions delete{' '}- {selectedFunction?.slug}- </>- )- },- comment: 'Delete the function',- },- ]-- const secretCommands: any = [- {- command: `supabase secrets list`,- description: 'This will list all the secrets for your project',- jsx: () => {- return (- <>- <span className="text-brand-1100">supabase</span> secrets list- </>- )- },- comment: 'View all secrets',- },- {- command: `supabase secrets set NAME1=VALUE1 NAME2=VALUE2`,- description: 'This will set secrets for your project',- jsx: () => {- return (- <>- <span className="text-brand-1100">supabase</span> secrets set NAME1=VALUE1 NAME2=VALUE2- </>- )- },- comment: 'Set secrets for your project',- },- {- command: `supabase secrets unset NAME1 NAME2 `,- description: 'This will delete secrets for your project',- jsx: () => {- return (- <>- <span className="text-brand-1100">supabase</span> secrets unset NAME1 NAME2- </>- )- },- comment: 'Unset secrets for your project',- },- ]-- const invokeCommands: any = [- {- command: `curl -L -X POST '${functionUrl}' -H 'Authorization: Bearer ${- anonKey ?? '[YOUR ANON KEY]'- }' --data '{"name":"Functions"}'`,- description: 'Invokes the hello function',- jsx: () => {- return (- <>- <span className="text-brand-1100">curl</span> -L -X POST 'https://{functionsEndpoint}/- {selectedFunction?.slug}' -H 'Authorization: Bearer [YOUR ANON KEY]'{' '}- {`--data '{"name":"Functions"}'`}- </>- )- },- comment: 'Invoke your function',- },- ]-return (<><div className="space-y-4 pb-16">- <Form id={formId} initialValues={{}} onSubmit={() => {}}>+ <Form id={formId} initialValues={{}} onSubmit={onUpdateFunction}>{({ isSubmitting, handleReset, values, initialValues, resetForm }: any) => {const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)@@ -186,7 +130,6 @@ const EdgeFunctionDetails: FC<Props> = () => {const formValues = {name: selectedFunction?.name,verifyJwt: selectedFunction?.verify_jwt,- importMap: selectedFunction?.import_map,}resetForm({ values: formValues, initialValues: formValues })}@@ -214,6 +157,13 @@ const EdgeFunctionDetails: FC<Props> = () => {<FormSection header={<FormSectionLabel>Function Details</FormSectionLabel>}><FormSectionContent loading={selectedFunction === undefined}><Input id="name" name="name" label="Name" />+ <Input+ disabled+ id="slug"+ name="slug"+ label="Slug"+ value={selectedFunction?.slug}+ /><Inputdisabledcopy@@ -247,6 +197,7 @@ const EdgeFunctionDetails: FC<Props> = () => {descriptionText="Require a valid JWT in the authorization header when invoking the function"/><Toggle+ disabledid="importMap"name="importMap"label={@@ -263,6 +214,7 @@ const EdgeFunctionDetails: FC<Props> = () => {</Link></div>}+ checked={selectedFunction?.import_map}descriptionText="Allow the use of bare specifiers without having to install the Node.js package locally"/></FormSectionContent>@@ -301,46 +253,49 @@ const EdgeFunctionDetails: FC<Props> = () => {<CommandRender commands={secretCommands} /></div>- <Panel title={<p>Delete Edge Function</p>} className="!mt-8">- <Panel.Content>- <Alert- withIcon- variant="danger"- title="Once your function is deleted, it can no longer be restored"- >- <p className="mb-3">- Make sure you have made a backup if you want to restore your edge function- </p>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger>- <Button- type="danger"- disabled={!canUpdateEdgeFunction}- loading={selectedFunction?.id === undefined}- onClick={() => setShowDeleteModal(true)}- >- Delete edge function- </Button>- </Tooltip.Trigger>- {!canUpdateEdgeFunction && (- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-scale-100 py-1 px-2 leading-none shadow',- 'border border-scale-200',- ].join(' ')}+ <div className="!mt-8">+ <FormHeader title="Delete Edge Function" description="" />+ <Panel>+ <Panel.Content>+ <Alert+ withIcon+ variant="danger"+ title="Once your function is deleted, it can no longer be restored"+ >+ <p className="mb-3">+ Make sure you have made a backup if you want to restore your edge function+ </p>+ <Tooltip.Root delayDuration={0}>+ <Tooltip.Trigger>+ <Button+ type="danger"+ disabled={!canUpdateEdgeFunction}+ loading={selectedFunction?.id === undefined}+ onClick={() => setShowDeleteModal(true)}>- <span className="text-xs text-scale-1200">- You need additional permissions to delete an edge function- </span>- </div>- </Tooltip.Content>- )}- </Tooltip.Root>- </Alert>- </Panel.Content>- </Panel>+ Delete edge function+ </Button>+ </Tooltip.Trigger>+ {!canUpdateEdgeFunction && (+ <Tooltip.Content side="bottom">+ <Tooltip.Arrow className="radix-tooltip-arrow" />+ <div+ className={[+ 'rounded bg-scale-100 py-1 px-2 leading-none shadow',+ 'border border-scale-200',+ ].join(' ')}+ >+ <span className="text-xs text-scale-1200">+ You need additional permissions to delete an edge function+ </span>+ </div>+ </Tooltip.Content>+ )}+ </Tooltip.Root>+ </Alert>+ </Panel.Content>+ </Panel>+ </div></div><Modaldiff --git a/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.utils.tsx b/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.utils.tsxnew file mode 100644index 00000000000..bc2ae902432--- /dev/null+++ b/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.utils.tsx@@ -0,0 +1,93 @@+export const generateCLICommands = (+ selectedFunction: any,+ functionUrl: string,+ anonKey: string+) => {+ const managementCommands: any = [+ {+ command: `supabase functions deploy ${selectedFunction?.slug}`,+ description: 'This will overwrite the deployed function with your new function',+ jsx: () => {+ return (+ <>+ <span className="text-brand-1100">supabase</span> functions deploy{' '}+ {selectedFunction?.slug}+ </>+ )+ },+ comment: 'Deploy a new version',+ },+ {+ command: `supabase functions delete ${selectedFunction?.slug}`,+ description: 'This will remove the function and all the logs associated with it',+ jsx: () => {+ return (+ <>+ <span className="text-brand-1100">supabase</span> functions delete{' '}+ {selectedFunction?.slug}+ </>+ )+ },+ comment: 'Delete the function',+ },+ ]++ const secretCommands: any = [+ {+ command: `supabase secrets list`,+ description: 'This will list all the secrets for your project',+ jsx: () => {+ return (+ <>+ <span className="text-brand-1100">supabase</span> secrets list+ </>+ )+ },+ comment: 'View all secrets',+ },+ {+ command: `supabase secrets set NAME1=VALUE1 NAME2=VALUE2`,+ description: 'This will set secrets for your project',+ jsx: () => {+ return (+ <>+ <span className="text-brand-1100">supabase</span> secrets set NAME1=VALUE1 NAME2=VALUE2+ </>+ )+ },+ comment: 'Set secrets for your project',+ },+ {+ command: `supabase secrets unset NAME1 NAME2 `,+ description: 'This will delete secrets for your project',+ jsx: () => {+ return (+ <>+ <span className="text-brand-1100">supabase</span> secrets unset NAME1 NAME2+ </>+ )+ },+ comment: 'Unset secrets for your project',+ },+ ]++ const invokeCommands: any = [+ {+ command: `curl -L -X POST '${functionUrl}' -H 'Authorization: Bearer ${+ anonKey ?? '[YOUR ANON KEY]'+ }' --data '{"name":"Functions"}'`,+ description: 'Invokes the hello function',+ jsx: () => {+ return (+ <>+ <span className="text-brand-1100">curl</span> -L -X POST '{functionUrl}' -H+ 'Authorization: Bearer [YOUR ANON KEY]' {`--data '{"name":"Functions"}'`}+ </>+ )+ },+ comment: 'Invoke your function',+ },+ ]++ return { managementCommands, secretCommands, invokeCommands }+}diff --git a/studio/components/interfaces/Functions/index.ts b/studio/components/interfaces/Functions/index.tsindex 003d5feaca6..992b396e1be 100644--- a/studio/components/interfaces/Functions/index.ts+++ b/studio/components/interfaces/Functions/index.ts@@ -1,4 +1,4 @@-import EdgeFunctionDetails from './EdgeFunctionDetails'+import EdgeFunctionDetails from './EdgeFunctionDetails/EdgeFunctionDetails'import EdgeFunctionsListItem from './EdgeFunctionsListItem'import FunctionsEmptyState from './FunctionsEmptyState'import TerminalInstructions from './TerminalInstructions'diff --git a/studio/components/layouts/FunctionsLayout.tsx b/studio/components/layouts/FunctionsLayout.tsxindex 0dc242cd836..1258b348505 100644--- a/studio/components/layouts/FunctionsLayout.tsx+++ b/studio/components/layouts/FunctionsLayout.tsx@@ -1,15 +1,15 @@import Link from 'next/link'-import { useRouter } from 'next/router'-import { FC, useEffect, ReactNode, useState } from 'react'+import { FC, ReactNode, useState } from 'react'import { observer } from 'mobx-react-lite'import { Button, IconExternalLink, IconCode, Modal, IconTerminal } from 'ui'-import { checkPermissions, useParams, useStore, withAuth } from 'hooks'+import { checkPermissions, useParams, withAuth } from 'hooks'import FunctionsNav from '../interfaces/Functions/FunctionsNav'import BaseLayout from 'components/layouts'import NoPermission from 'components/ui/NoPermission'import { PermissionAction } from '@supabase/shared-types/out/constants'import { TerminalInstructions } from 'components/interfaces/Functions'+import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'interface Props {title?: string@@ -17,14 +17,9 @@ interface Props {}const FunctionsLayout: FC<Props> = ({ title, children }) => {- const router = useRouter()const { id, ref } = useParams()- const { functions, ui } = useStore()const [showTerminalInstructions, setShowTerminalInstructions] = useState(false)-- useEffect(() => {- if (ui.selectedProjectRef) functions.load()- }, [ui.selectedProjectRef])+ const { isLoading, data: functions } = useEdgeFunctionsQuery({ projectRef: ref })const canReadFunctions = checkPermissions(PermissionAction.FUNCTIONS_READ, '*')if (!canReadFunctions) {@@ -37,18 +32,14 @@ const FunctionsLayout: FC<Props> = ({ title, children }) => {)}- const item = id ? functions.byId(id) : null+ const item = id ? (functions ?? []).find((fn) => fn.id === id) : nullconst name = item?.name || ''- const hasFunctions = functions.list().length > 0+ const hasFunctions = (functions ?? []).length > 0const centered = !hasFunctionsreturn (- <BaseLayout- isLoading={!functions.isLoaded}- title={title || 'Edge Functions'}- product="Edge Functions"- >+ <BaseLayout isLoading={isLoading} title={title || 'Edge Functions'} product="Edge Functions">{centered ? (<><div className="mx-auto max-w-5xl py-24 px-5">diff --git a/studio/data/edge-functions/edge-functions-update-mutation.tsx b/studio/data/edge-functions/edge-functions-update-mutation.tsxindex c16762bed25..4166a7ec3e8 100644--- a/studio/data/edge-functions/edge-functions-update-mutation.tsx+++ b/studio/data/edge-functions/edge-functions-update-mutation.tsx@@ -6,22 +6,21 @@ import { edgeFunctionsKeys } from './keys'export type EdgeFunctionsUpdateVariables = {projectRef: stringslug: string- verifyJwt?: boolean- importMap?: boolean+ payload: {+ name?: string+ verifyJwt?: boolean+ importMap?: boolean+ }}export async function updateEdgeFunction({projectRef,slug,- verifyJwt,- importMap,+ payload,}: EdgeFunctionsUpdateVariables) {if (!projectRef) throw new Error('projectRef is required')- const response = await patch(- `${API_ADMIN_URL}/projects/${projectRef}/functions/${slug}?verify_jwt=${verifyJwt}&import_map=${importMap}`,- {}- )+ const response = await patch(`${API_ADMIN_URL}/projects/${projectRef}/functions/${slug}`, payload)if (response.error) throw response.errorreturn response@@ -29,7 +28,7 @@ export async function updateEdgeFunction({type EdgeFunctionsUpdateData = Awaited<ReturnType<typeof updateEdgeFunction>>-export const useEdgeFunctionDeleteMutation = ({+export const useEdgeFunctionUpdateMutation = ({onSuccess,...options}: Omit<