Skip to content

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

Hook up upload logic

Joshen Lima743f35b55d9
diff --git a/studio/components/interfaces/Support/SupportForm.tsx b/studio/components/interfaces/Support/SupportForm.tsx
index ac115f5df5d..68e8d17dafa 100644
--- a/studio/components/interfaces/Support/SupportForm.tsx
+++ b/studio/components/interfaces/Support/SupportForm.tsx
@@ -11,7 +11,7 @@ import { API_URL, PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
import Divider from 'components/ui/Divider'
import Connecting from 'components/ui/Loading/Loading'
-import { formReducer, uploadAttachments } from './SupportForm.utils'
+import { formatMessage, formReducer, uploadAttachments } from './SupportForm.utils'
import {
DEFAULT_VALUES,
CATEGORY_OPTIONS,
@@ -124,16 +124,13 @@ const SupportForm: FC<Props> = ({ setSent }) => {
setErrors([...errors])
if (errors.length === 0) {
+ setLoading(true)
const projectRef = formState.project.value
-
- if (uploadedFiles) {
- const uploadedAttachments = await uploadAttachments(projectRef, uploadedFiles)
- console.log(uploadedAttachments)
- }
+ const attachments = uploadedFiles ? await uploadAttachments(projectRef, uploadedFiles) : []
const payload = {
projectRef,
- message: formState.body.value,
+ message: formatMessage(formState.body.value, attachments),
category: formState.category.value,
verified: true,
tags: ['dashboard-support-form'],
@@ -152,21 +149,18 @@ const SupportForm: FC<Props> = ({ setSent }) => {
}
}
- ui.setNotification({ category: 'success', message: 'hehe' })
-
- // setLoading(true)
- // const response = await post(`${API_URL}/feedback/send`, payload)
- // setLoading(false)
-
- // if (response.error) {
- // ui.setNotification({
- // category: 'error',
- // message: `Failed to submit support ticket: ${response.error.message}`,
- // })
- // } else {
- // ui.setNotification({ category: 'success', message: 'Support request sent. Thank you!' })
- // setSent(true)
- // }
+ const response = await post(`${API_URL}/feedback/send`, payload)
+ setLoading(false)
+
+ if (response.error) {
+ ui.setNotification({
+ category: 'error',
+ message: `Failed to submit support ticket: ${response.error.message}`,
+ })
+ } else {
+ ui.setNotification({ category: 'success', message: 'Support request sent. Thank you!' })
+ // setSent(true)
+ }
}
}
diff --git a/studio/components/interfaces/Support/SupportForm.utils.ts b/studio/components/interfaces/Support/SupportForm.utils.ts
index fe4815a0cf5..f1ebbbd3e1f 100644
--- a/studio/components/interfaces/Support/SupportForm.utils.ts
+++ b/studio/components/interfaces/Support/SupportForm.utils.ts
@@ -1,7 +1,25 @@
+import { compact } from 'lodash'
import { createClient } from '@supabase/supabase-js'
-import { IS_PLATFORM } from 'lib/constants'
import { uuidv4 } from 'lib/helpers'
-import { post } from 'lib/common/fetch'
+
+// [Joshen TODO] To be shifted into an env vars before doing anything
+// Both bitwarden, .env, and vercel
+const SUPPORT_API_URL = process.env.NEXT_PUBLIC_SUPPORT_API_URL || ''
+const SUPPORT_API_KEY = process.env.NEXT_PUBLIC_SUPPORT_ANON_KEY || ''
+const supportSupabaseClient = createClient(SUPPORT_API_URL, SUPPORT_API_KEY, {
+ auth: {
+ persistSession: false,
+ autoRefreshToken: false,
+ multiTab: false,
+ detectSessionInUrl: false,
+ localStorage: {
+ // @ts-ignore
+ getItem: (key) => {},
+ setItem: (key, value) => {},
+ removeItem: (key) => {},
+ },
+ },
+})
export function formReducer(state: any, action: any) {
return {
@@ -15,26 +33,41 @@ export function formReducer(state: any, action: any) {
export const uploadAttachments = async (ref: string, files: File[]) => {
const filesToUpload = Array.from(files)
- return Promise.all(
+ const uploadedFiles = await Promise.all(
filesToUpload.map(async (file) => {
- // [Joshen] Left off here - trying to figure out how to
- // pass the files into the next API, which will upload the files then through
- // the Supabase client
- const res = await post('/api/upload-attachments', files, {
- headers: { 'Content-Type': 'multipart/form-data' },
- })
+ const suffix = file.type.split('/')[1]
+ const prefix = `${ref}/${uuidv4()}.${suffix}`
+ const options = { cacheControl: '3600' }
- // const prefix = `${ref}/${uuidv4()}`
- // const options = { cacheControl: '3600' }
+ const { data, error } = await supportSupabaseClient.storage
+ .from('support-attachments')
+ .upload(prefix, file, options)
- // const { data, error } = await supportSupabaseClient.storage
- // .from('support-attachments')
- // .upload(prefix, file, options)
-
- // if (error) {
- // console.log('error', error)
- // }
- // return data
+ if (error) console.error('Failed to upload:', file.name, error)
+ return data
})
)
+ const keys = compact(uploadedFiles).map((file) => file.Key.split('/').slice(1).join('/'))
+
+ const { data, error } = await supportSupabaseClient.storage
+ .from('support-attachments')
+ .createSignedUrls(keys, 10 * 365 * 24 * 60 * 60)
+ if (error) {
+ console.error('Failed to retrieve URLs for attachments', error)
+ }
+ return data ? data.map((file) => file.signedURL) : []
+}
+
+export const formatMessage = (message: string, attachments: string[]) => {
+ const formattedMessage = message.replace(/\n/g, '<br/>')
+ if (attachments.length > 0) {
+ const attachmentsImg = attachments.map(
+ (url) => `<img src=${url} width="200" style="margin-right:10px" />`
+ )
+ return `${formattedMessage}<br/><hr/><b>Uploaded attachments:</b><br/><div style="display:flex;align-items:center">${attachmentsImg.join(
+ ''
+ )}</div>`
+ } else {
+ return formattedMessage
+ }
}
diff --git a/studio/pages/api/upload-attachments.tsx b/studio/pages/api/upload-attachments.tsx
deleted file mode 100644
index 90ca3aa6255..00000000000
--- a/studio/pages/api/upload-attachments.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { NextApiRequest, NextApiResponse } from 'next'
-import { createClient } from '@supabase/supabase-js'
-import SqlString from 'sqlstring'
-
-import apiWrapper from 'lib/api/apiWrapper'
-import { IS_PLATFORM } from 'lib/constants'
-import { constructHeaders } from 'lib/api/apiHelpers'
-import { post } from 'lib/common/fetch'
-import { tryParseInt } from 'lib/helpers'
-
-// [Joshen TODO] To be shifted into an env vars before doing anything
-// Both bitwarden, .env, and vercel
-const API_URL = 'https://mfrkmguhoejspftfvgdz.supabase.co'
-const API_KEY =
- 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlhdCI6MTYyNzg4NjQ0MCwiZXhwIjoxOTQzNDYyNDQwfQ.wRGmWXOORz-cxVBof4WLOSxRog9Tdff1P8gI72U8ta8'
-
-export default (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
-
-async function handler(req: NextApiRequest, res: NextApiResponse) {
- const { method } = req
-
- switch (method) {
- case 'POST':
- return handlePost(req, res)
- default:
- res.setHeader('Allow', ['POST'])
- res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })
- }
-}
-
-const handlePost = async (req: NextApiRequest, res: NextApiResponse) => {
- if (!IS_PLATFORM) return res.status(200).json({})
-
- const supportSupabaseClient = createClient(API_URL, API_KEY)
- console.log('Upload attachments', req.body)
-
- console.log()
- console.log('Files', req.body.files[0])
- console.log()
-
- return res.status(200).json({ ping: 'pong' })
-}