Skip to content

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

Chore/fix cron job card (#32767)

Joshen Limd9a7b43cac2b
diff --git a/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/AddRLSPolicyForFirebaseDialog.tsx b/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/AddRLSPolicyForFirebaseDialog.tsx
deleted file mode 100644
index 3f98c84a003..00000000000
--- a/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/AddRLSPolicyForFirebaseDialog.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { copyToClipboard } from 'lib/helpers'
-import { Check } from 'lucide-react'
-import Link from 'next/link'
-import { useEffect, useState } from 'react'
-import {
- Button,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogSection,
- DialogSectionSeparator,
- DialogTitle,
-} from 'ui'
-import { SQLCodeBlock } from './SqlCodeBlock'
-
-export const AddRLSPolicyForFirebaseDialog = ({
- projectRef,
- firebaseProjectId,
-}: {
- projectRef: string
- firebaseProjectId: string
-}) => {
- const description = `create policy
- "Restrict access to Firebase Auth for project ID ${firebaseProjectId}"
- on table_name
- as restrictive
- to authenticated using (
- (
- auth.jwt()->>'iss' = 'https://${projectRef}.supabase.co/auth/v1'
- )
- or (
- auth.jwt()->>'iss' = 'https://securetoken.google.com/${firebaseProjectId}'
- and auth.jwt()->>'aud' = '${firebaseProjectId}'
- )
-);`
-
- const [copied, setCopied] = useState(false)
-
- useEffect(() => {
- if (!copied) return
- const timer = setTimeout(() => setCopied(false), 2000)
- return () => clearTimeout(timer)
- }, [copied])
-
- function handleCopy(formatted: string) {
- copyToClipboard(formatted, () => setCopied(true))
- }
-
- return (
- <>
- <DialogHeader padding={'small'}>
- <DialogTitle>Add RLS policy</DialogTitle>
- <DialogDescription>
- We recommend adding a Row Level Security (RLS) policy for your Firebase JWT keys to
- explicitly specify which tables can be accessed via the Data APIs in order to prevent
- accidental exposure of data.
- </DialogDescription>
- </DialogHeader>
- <DialogSectionSeparator />
- <DialogSection padding={'small'}>
- <SQLCodeBlock>{[description]}</SQLCodeBlock>
- </DialogSection>
- <DialogFooter padding={'small'}>
- <Button
- type="default"
- onClick={() => handleCopy(description)}
- icon={copied ? <Check className="text-brand-600" /> : null}
- >
- {copied ? <p>Copied</p> : <p>Copy code</p>}
- </Button>
- <Button type="primary">
- <Link
- href={`/project/${projectRef}/sql/new?content=${encodeURIComponent(description)}`}
- passHref
- >
- Open in SQL Editor
- </Link>
- </Button>
- </DialogFooter>
- </>
- )
-}
diff --git a/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/IntegrationCard.tsx b/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/IntegrationCard.tsx
index 97156cfe595..aab6710eec1 100644
--- a/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/IntegrationCard.tsx
+++ b/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/IntegrationCard.tsx
@@ -1,11 +1,9 @@
-import { ExclamationCircleIcon } from '@heroicons/react/16/solid'
import { Check } from 'lucide-react'
import Image from 'next/image'
import { useParams } from 'common'
import { ThirdPartyAuthIntegration } from 'data/third-party-auth/integrations-query'
-import { Badge, Button, Dialog, DialogContent, DialogTrigger } from 'ui'
-import { AddRLSPolicyForFirebaseDialog } from './AddRLSPolicyForFirebaseDialog'
+import { Badge, Button } from 'ui'
import { AWS_IDP_REGIONS } from './AwsRegionSelector'
import {
getIntegrationType,
diff --git a/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/SqlCodeBlock.tsx b/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/SqlCodeBlock.tsx
deleted file mode 100644
index c0afb0d5e71..00000000000
--- a/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/SqlCodeBlock.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { format } from 'sql-formatter'
-import { CodeBlock, cn } from 'ui'
-
-interface SQLCodeBlockProps {
- children: string[]
- className?: string
-}
-
-export const SQLCodeBlock = ({ children, className }: SQLCodeBlockProps) => {
- let formatted = (children || [''])[0]
- try {
- formatted = format(formatted, {
- language: 'postgresql',
- keywordCase: 'upper',
- })
- } catch {}
-
- if (formatted.length === 0) {
- return null
- }
-
- return (
- <pre className="rounded-md relative group">
- <CodeBlock
- value={formatted}
- language="sql"
- className={cn(
- 'py-3 px-3.5 prose dark:prose-dark transition max-w-full',
- // change the look of the code block. The flex hack is so that the code is wrapping since
- // every word is a separate span
- '[&>code]:m-0 [&>code>span]:flex [&>code>span]:flex-wrap',
- className
- )}
- hideCopy
- hideLineNumbers
- />
- </pre>
- )
-}
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet.tsx
index 51499cce162..ec9e3897737 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet.tsx
@@ -1,11 +1,12 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { toString as CronToString } from 'cronstrue'
-import { useState } from 'react'
+import { useEffect, useState } from 'react'
import { SubmitHandler, useForm } from 'react-hook-form'
import { toast } from 'sonner'
import z from 'zod'
+import { useWatch } from '@ui/components/shadcn/ui/form'
import { urlRegex } from 'components/interfaces/Auth/Auth.constants'
import EnableExtensionModal from 'components/interfaces/Database/Extensions/EnableExtensionModal'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
@@ -77,6 +78,8 @@ const edgeFunctionSchema = z.object({
return false
}
}, 'Input must be valid JSON'),
+ // When editing a cron job, we want to keep the original command as a snippet in case the user wants to manually edit it
+ snippet: z.string().trim(),
})
const httpRequestSchema = z.object({
@@ -103,12 +106,16 @@ const httpRequestSchema = z.object({
return false
}
}, 'Input must be valid JSON'),
+ // When editing a cron job, we want to keep the original command as a snippet in case the user wants to manually edit it
+ snippet: z.string().trim(),
})
const sqlFunctionSchema = z.object({
type: z.literal('sql_function'),
schema: z.string().trim().min(1, 'Please select one of the listed database schemas'),
functionName: z.string().trim().min(1, 'Please select one of the listed database functions'),
+ // When editing a cron job, we want to keep the original command as a snippet in case the user wants to manually edit it
+ snippet: z.string().trim(),
})
const sqlSnippetSchema = z.object({
type: z.literal('sql_snippet'),
@@ -160,6 +167,30 @@ export type CronJobType = CreateCronJobForm['values']
const FORM_ID = 'create-cron-job-sidepanel'
+const buildCommand = (values: CronJobType) => {
+ let command = ''
+ if (values.type === 'edge_function') {
+ command = buildHttpRequestCommand(
+ values.method,
+ values.edgeFunctionName,
+ values.httpHeaders,
+ values.httpBody,
+ values.timeoutMs
+ )
+ } else if (values.type === 'http_request') {
+ command = buildHttpRequestCommand(
+ values.method,
+ values.endpoint,
+ values.httpHeaders,
+ values.httpBody,
+ values.timeoutMs
+ )
+ } else if (values.type === 'sql_function') {
+ command = `CALL ${values.schema}.${values.functionName}()`
+ }
+ return command
+}
+
export const CreateCronJobSheet = ({
selectedCronJob,
supportsSeconds,
@@ -185,7 +216,7 @@ export const CreateCronJobSheet = ({
'extensions'
)
- const cronJobValues = parseCronJobCommand(selectedCronJob?.command || '')
+ const cronJobValues = parseCronJobCommand(selectedCronJob?.command || '', project?.ref!)
const form = useForm<CreateCronJobForm>({
resolver: zodResolver(FormSchema),
@@ -212,6 +243,61 @@ export const CreateCronJobSheet = ({
}
}
+ const [
+ cronType,
+ endpoint,
+ edgeFunctionName,
+ method,
+ httpHeaders,
+ httpBody,
+ timeoutMs,
+ schema,
+ functionName,
+ ] = useWatch({
+ control: form.control,
+ name: [
+ 'values.type',
+ 'values.endpoint',
+ 'values.edgeFunctionName',
+ 'values.method',
+ 'values.httpHeaders',
+ 'values.httpBody',
+ 'values.timeoutMs',
+ 'values.schema',
+ 'values.functionName',
+ ],
+ })
+
+ // update the snippet field when the user changes the any values in the form
+ useEffect(() => {
+ const command = buildCommand({
+ type: cronType,
+ method,
+ edgeFunctionName,
+ timeoutMs,
+ httpHeaders,
+ httpBody,
+ functionName,
+ schema,
+ endpoint,
+ snippet: '',
+ })
+ if (command) {
+ form.setValue('values.snippet', command)
+ }
+ }, [
+ edgeFunctionName,
+ endpoint,
+ method,
+ // for some reason, the httpHeaders are not memoized and cause the useEffect to trigger even when the value is the same
+ JSON.stringify(httpHeaders),
+ httpBody,
+ timeoutMs,
+ schema,
+ functionName,
+ form,
+ ])
+
const onSubmit: SubmitHandler<CreateCronJobForm> = async ({ name, schedule, values }) => {
// job names should be unique
const nameExists = cronJobs?.some(
@@ -225,28 +311,7 @@ export const CreateCronJobSheet = ({
return
}
- let command = ''
- if (values.type === 'edge_function') {
- command = buildHttpRequestCommand(
- values.method,
- values.edgeFunctionName,
- values.httpHeaders,
- values.httpBody,
- values.timeoutMs
- )
- } else if (values.type === 'http_request') {
- command = buildHttpRequestCommand(
- values.method,
- values.endpoint,
- values.httpHeaders,
- values.httpBody,
- values.timeoutMs
- )
- } else if (values.type === 'sql_function') {
- command = `'CALL ${values.schema}.${values.functionName}()'`
- } else {
- command = `$$${values.snippet}$$`
- }
+ let command = `$$${values.snippet}$$`
const query = buildCronQuery(name, schedule, command)
@@ -296,8 +361,6 @@ export const CreateCronJobSheet = ({
const pgNetExtension = (data ?? []).find((ext) => ext.name === 'pg_net')
const pgNetExtensionInstalled = pgNetExtension?.installed_version != undefined
- const cronType = form.watch('values.type')
-
return (
<>
<div className="flex flex-col h-full" tabIndex={-1}>
@@ -345,7 +408,7 @@ export const CreateCronJobSheet = ({
name="function_type"
value={field.value}
disabled={field.disabled}
- onValueChange={field.onChange}
+ onValueChange={(value) => field.onChange(value)}
>
{CRONJOB_DEFINITIONS.map((definition) => (
<RadioGroupStackedItem
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobCard.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobCard.tsx
index 98a830bf9e4..8cb42e571e6 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobCard.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobCard.tsx
@@ -4,7 +4,6 @@ import Link from 'next/link'
import { useState } from 'react'
import { useParams } from 'common'
-import { SQLCodeBlock } from 'components/interfaces/Auth/ThirdPartyAuthForm/SqlCodeBlock'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { CronJob } from 'data/database-cron-jobs/database-cron-jobs-query'
import { useCronJobRunQuery } from 'data/database-cron-jobs/database-cron-jobs-run-query'
@@ -15,6 +14,7 @@ import {
Badge,
Button,
cn,
+ CodeBlock,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
@@ -191,7 +191,15 @@ export const CronJobCard = ({ job, onEditCronJob, onDeleteCronJob }: CronJobCard
<div className="grid grid-cols-10 gap-3">
<span className="text-foreground-light col-span-1">Command</span>
<div className="col-span-9">
- <SQLCodeBlock className="py-2">{[job.command.trim()]}</SQLCodeBlock>
+ <CodeBlock
+ hideLineNumbers
+ value={job.command.trim()}
+ language="sql"
+ className={cn(
+ 'py-2 px-3.5 max-w-full prose dark:prose-dark',
+ '[&>code]:m-0 [&>code>span]:flex [&>code>span]:flex-wrap min-h-11'
+ )}
+ />
</div>
</div>
</div>
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.test.ts b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.test.ts
index 5108f345ce0..9b996b91bf9 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.test.ts
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.test.ts
@@ -3,12 +3,18 @@ import { cronPattern, parseCronJobCommand, secondsPattern } from './CronJobs.uti
describe('parseCronJobCommand', () => {
it('should return a default object when the command is null', () => {
- expect(parseCronJobCommand('')).toMatchObject({ snippet: '', type: 'sql_snippet' })
+ expect(parseCronJobCommand('', 'random_project_ref')).toStrictEqual({
+ httpBody: '',
+ method: 'POST',
+ snippet: '',
+ timeoutMs: 1000,
+ type: 'sql_snippet',
+ })
})
it('should return a default object when the command is random', () => {
const command = 'some random text'
- expect(parseCronJobCommand(command)).toMatchObject({
+ expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({
snippet: 'some random text',
type: 'sql_snippet',
})
@@ -16,70 +22,124 @@ describe('parseCronJobCommand', () => {
it('should return a sql function command when the command is CALL auth.jwt ()', () => {
const command = 'CALL auth.jwt ()'
- expect(parseCronJobCommand(command)).toMatchObject({
+ expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({
type: 'sql_function',
schema: 'auth',
functionName: 'jwt',
+ snippet: command,
})
})
- it('should return a edge function config when the command posts to supabase.co', () => {
- const command = `select net.http_post( url:='https://_.supabase.co/functions/v1/_', headers:=jsonb_build_object(), body:='', timeout_milliseconds:=5000 );`
- expect(parseCronJobCommand(command)).toMatchObject({
- edgeFunctionName: 'https://_.supabase.co/functions/v1/_',
+ it('should return a edge function config when the command posts to its own supabase.co project', () => {
+ const command = `select net.http_post( url:='https://random_project_ref.supabase.co/functions/v1/_', headers:=jsonb_build_object(), body:='', timeout_milliseconds:=5000 );`
+ expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({
+ edgeFunctionName: 'https://random_project_ref.supabase.co/functions/v1/_',
method: 'POST',
httpHeaders: [],
httpBody: '',
timeoutMs: 5000,
type: 'edge_function',
+ snippet: command,
+ })
+ })
+
+ it('should return a HTTP request config when the command posts to another supabase.co project', () => {
+ const command = `select net.http_post( url:='https://another_project_ref.supabase.co/functions/v1/_', headers:=jsonb_build_object(), body:='', timeout_milliseconds:=5000 );`
+ expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({
+ endpoint: 'https://another_project_ref.supabase.co/functions/v1/_',
+ method: 'POST',
+ httpHeaders: [],
+ httpBody: '',
+ timeoutMs: 5000,
+ type: 'http_request',
+ snippet: command,
})
})
it('should return a HTTP request config with POST method, empty headers and a body as string', () => {
const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object(), body:='hello', timeout_milliseconds:=5000 );`
- expect(parseCronJobCommand(command)).toMatchObject({
+ expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({
endpoint: 'https://example.com/api/endpoint',
method: 'POST',
httpHeaders: [],
httpBody: 'hello',
timeoutMs: 5000,
type: 'http_request',
+ snippet: command,
})
})
it('should return a HTTP request config with POST method, some headers and empty body', () => {
- const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('headerche', '2'), body:='', timeout_milliseconds:=1000 );`
- expect(parseCronJobCommand(command)).toMatchObject({
+ const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('fst', '1', 'snd', '2'), body:='', timeout_milliseconds:=1000 );`
+ expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({
endpoint: 'https://example.com/api/endpoint',
method: 'POST',
- httpHeaders: [{ name: 'headerche', value: '2' }],
+ httpHeaders: [
+ { name: 'fst', value: '1' },
+ { name: 'snd', value: '2' },
+ ],
httpBody: '',
timeoutMs: 1000,
type: 'http_request',
+ snippet: command,
})
})
it('should return a HTTP request config with GET method and empty body', () => {
const command = `select net.http_get( url:='https://example.com/api/endpoint', headers:=jsonb_build_object(), timeout_milliseconds:=5000 );`
- expect(parseCronJobCommand(command)).toMatchObject({
+ expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({
endpoint: 'https://example.com/api/endpoint',
method: 'GET',
httpHeaders: [],
httpBody: '',
timeoutMs: 5000,
type: 'http_request',
+ snippet: command,
})
})
it('should return a HTTP request config with POST method and a body as JSON object', () => {
const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object(), body:='{"key": "value"}', timeout_milliseconds:=5000 );`
- expect(parseCronJobCommand(command)).toMatchObject({
+ expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({
endpoint: 'https://example.com/api/endpoint',
method: 'POST',
httpHeaders: [],
httpBody: '{"key": "value"}',
timeoutMs: 5000,
type: 'http_request',
+ snippet: command,
+ })
+ })
+
+ it('should return a HTTP request config with POST method, plain JSON headers and plain JSON body', () => {
+ const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:='{"fst": "1", "snd": "2"}',body:='{"key": "value"}',timeout_milliseconds:=5000);`
+ expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({
+ endpoint: 'https://example.com/api/endpoint',
+ method: 'POST',
+ httpHeaders: [
+ { name: 'fst', value: '1' },
+ { name: 'snd', value: '2' },
+ ],
+ httpBody: '{"key": "value"}',
+ timeoutMs: 5000,
+ type: 'http_request',
+ snippet: command,
+ })
+ })
+
+ it('should return a HTTP request config with POST method, plain JSON headers and plain JSON body with ::jsonb typecasting', () => {
+ const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:='{"fst": "1", "snd": "2"}'::jsonb,body:='{"key": "value"}'::jsonb,timeout_milliseconds:=5000);`
+ expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({
+ endpoint: 'https://example.com/api/endpoint',
+ method: 'POST',
+ httpHeaders: [
+ { name: 'fst', value: '1' },
+ { name: 'snd', value: '2' },
+ ],
+ httpBody: '{"key": "value"}',
+ timeoutMs: 5000,
+ type: 'http_request',
+ snippet: command,
})
})
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.ts b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.ts
index 1fe6de9099b..25f0ff6d043 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.ts
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.ts
@@ -16,18 +16,16 @@ export const buildHttpRequestCommand = (
body: string | undefined,
timeout: number
) => {
- return `$$
- select
- net.${method === 'GET' ? 'http_get' : 'http_post'}(
- url:='${url}',
- headers:=jsonb_build_object(${headers
- .filter((v) => v.name && v.value)
- .map((v) => `'${v.name}', '${v.value}'`)
- .join(', ')}),
- ${method === 'POST' && body ? `body:='${body}',` : ''}
- timeout_milliseconds:=${timeout}
- );
- $$`
+ return `
+select
+ net.${method === 'GET' ? 'http_get' : 'http_post'}(
+ url:='${url}',
+ headers:=jsonb_build_object(${headers
+ .filter((v) => v.name && v.value)
+ .map((v) => `'${v.name}', '${v.value}'`)
+ .join(', ')}), ${method === 'POST' && body ? `\n body:='${body}',` : ''}
+ timeout_milliseconds:=${timeout}
+ );`
}
const DEFAULT_CRONJOB_COMMAND = {
@@ -39,7 +37,7 @@ const DEFAULT_CRONJOB_COMMAND = {
httpBody: '',
} as const
-export const parseCronJobCommand = (originalCommand: string): CronJobType => {
+export const parseCronJobCommand = (originalCommand: string, projectRef: string): CronJobType => {
const command = originalCommand
.replaceAll('$$', ' ')
.replaceAll(/\n/g, ' ')
@@ -47,51 +45,65 @@ export const parseCronJobCommand = (originalCommand: string): CronJobType => {
.trim()
if (command.toLocaleLowerCase().startsWith('select net.')) {
- let matches =
- command.match(
- /select net\.([^']+)\(\s*url:='([^']+)',\s*headers:=jsonb_build_object\(([^)]*)\),(?:\s*body:='(.*)',)?\s*timeout_milliseconds:=(\d+) \)/i
- ) || []
-
- // if the match has been unsuccessful, the cron may be created with the previous encoding/parsing.
- if (matches.length === 0) {
- matches =
- command.match(
- /select net\.([^']+)\(\s*url:='([^']+)',\s*headers:=jsonb_build_object\(([^)]*)\),\s*body:=jsonb_build_object\(([^]*)\s*\),\s*timeout_milliseconds:=(\d+) \)/i
- ) || []
- }
+ const methodMatch = command.match(/select net\.([^']+)\(\s*url:=/i)
+ const method = methodMatch?.[1] || ''
+
+ const urlMatch = command.match(/url:='([^']+)'/i)
+ const url = urlMatch?.[1] || ''
+
+ const bodyMatch = command.match(/body:='(.*)'/i)
+ const body = bodyMatch?.[1] || ''
+
+ const timeoutMatch = command.match(/timeout_milliseconds:=(\d+)/i)
+ const timeout = timeoutMatch?.[1] || ''
+
+ const headersJsonBuildObjectMatch = command.match(/headers:=jsonb_build_object\(([^)]*)/i)
+ const headersJsonBuildObject = headersJsonBuildObjectMatch?.[1] || ''
+
+ let headersObjs: { name: string; value: string }[] = []
+ if (headersJsonBuildObject) {
+ // convert the header string to array of objects, clean up the values, trim them of spaces and remove the quotation marks at start and end
+ const headers = headersJsonBuildObject.split(',').map((s) => s.trim().replace(/^'|'$/g, ''))
- // convert the header string to array of objects, clean up the values, trim them of spaces and remove the quotation marks at start and end
- const headers = (matches[3] || '').split(',').map((s) => s.trim().replace(/^'|'$/g, ''))
- const headersObjs: { name: string; value: string }[] = []
- for (let i = 0; i < headers.length; i += 2) {
- if (headers[i] && headers[i].length > 0) {
- headersObjs.push({ name: headers[i], value: headers[i + 1] })
+ for (let i = 0; i < headers.length; i += 2) {
+ if (headers[i] && headers[i].length > 0) {
+ headersObjs.push({ name: headers[i], value: headers[i + 1] })
+ }
+ }
+ } else {
+ const headersStringMatch = command.match(/headers:='([^']*)'/i)
+ const headersString = headersStringMatch?.[1] || ''
+ try {
+ const parsedHeaders = JSON.parse(headersString)
+ headersObjs = Object.entries(parsedHeaders).map(([name, value]) => ({
+ name,
+ value: value as string,
+ }))
+ } catch (error) {
+ console.error('Error parsing headers:', error)
}
}
- const url = matches[2] || ''
- const body = matches[4] || ''
-
- if (url.includes('.supabase.') && url.includes('/functions/v1/')) {
+ if (url.includes(`${projectRef}.supabase.`) && url.includes('/functions/v1/')) {
return {
type: 'edge_function',
- method: matches[1] === 'http_get' ? 'GET' : 'POST',
+ method: method === 'http_get' ? 'GET' : 'POST',
edgeFunctionName: url,
httpHeaders: headersObjs,
httpBody: body,
- // @ts-ignore
- timeoutMs: +matches[5] ?? 1000,
+ timeoutMs: +timeout ?? 1000,
+ snippet: originalCommand,
}
}
return {
type: 'http_request',
- method: matches[1] === 'http_get' ? 'GET' : 'POST',
+ method: method === 'http_get' ? 'GET' : 'POST',
endpoint: url,
httpHeaders: headersObjs,
httpBody: body,
- // @ts-ignore
- timeoutMs: +matches[5] ?? 1000,
+ timeoutMs: +timeout ?? 1000,
+ snippet: originalCommand,
}
}
@@ -106,6 +118,7 @@ export const parseCronJobCommand = (originalCommand: string): CronJobType => {
type: 'sql_function',
schema: schemaName,
functionName: functionName,
+ snippet: originalCommand,
}
}
diff --git a/apps/studio/data/database-cron-jobs/database-cron-jobs-run-query.ts b/apps/studio/data/database-cron-jobs/database-cron-jobs-run-query.ts
index aaa92df92e2..ef31e6e2d96 100644
--- a/apps/studio/data/database-cron-jobs/database-cron-jobs-run-query.ts
+++ b/apps/studio/data/database-cron-jobs/database-cron-jobs-run-query.ts
@@ -30,10 +30,10 @@ export async function getDatabaseCronJobRun({
sql: query,
})
- return result[0]
+ return result[0] ?? null
}
-export type DatabaseCronJobRunData = CronJobRun
+export type DatabaseCronJobRunData = CronJobRun | null
export type DatabaseCronJobRunError = ResponseError
export const useCronJobRunQuery = <TData = DatabaseCronJobRunData>(