diff --git a/myfavstuff/app/add-item/actions.js b/myfavstuff/app/add-item/actions.js index 1687f3f..d0e591e 100644 --- a/myfavstuff/app/add-item/actions.js +++ b/myfavstuff/app/add-item/actions.js @@ -6,16 +6,54 @@ import { revalidatePath } from 'next/cache'; import { redirect } from 'next/navigation'; export async function createItem(formData) { + const BUCKET_NAME = 'item_images'; if (!supabase) { return { error: 'Supabase client is not initialized. Cannot create item.' }; } + const pictureFile = formData.get('picture_file'); + let pictureUrl = null; + + if (pictureFile && pictureFile.size > 0) { + if (!supabase.storage) { + return { error: 'Supabase storage client is not available.' }; + } + const fileName = `public/${Date.now()}-${pictureFile.name.replace(/[^a-zA-Z0-9.]/g, '_')}`; + const { data: uploadData, error: uploadError } = await supabase.storage + .from(BUCKET_NAME) + .upload(fileName, pictureFile); + + if (uploadError) { + console.error('Supabase storage upload error:', uploadError); + return { error: `Failed to upload image: ${uploadError.message}` }; + } + + const { data: publicUrlData } = supabase.storage + .from(BUCKET_NAME) + .getPublicUrl(fileName); + + if (!publicUrlData || !publicUrlData.publicUrl) { + console.error('Supabase storage getPublicUrl error: No publicUrl found'); + // Optionally, you might want to delete the uploaded file here if getting URL fails + // await supabase.storage.from(BUCKET_NAME).remove([fileName]); + return { error: 'Failed to get image public URL after upload.' }; + } + pictureUrl = publicUrlData.publicUrl; + } else { + // Handle case where no file is uploaded but form still has 'picture_url' field (e.g. from old version) + // Or simply rely on pictureUrl being null if no file is chosen. + const legacyPictureUrl = formData.get('picture_url'); + if (legacyPictureUrl && typeof legacyPictureUrl === 'string' && legacyPictureUrl.startsWith('http')) { + pictureUrl = legacyPictureUrl; // Keep old URL if provided and no new file + } + } + const newItem = { title: formData.get('title'), type: formData.get('type'), rating: formData.get('rating') ? parseInt(formData.get('rating'), 10) : null, notes: formData.get('notes'), - picture_url: formData.get('picture_url'), + picture_url: pictureUrl, // created_at will be set by default in Supabase or can be added here if needed }; diff --git a/myfavstuff/app/add-item/page.js b/myfavstuff/app/add-item/page.js index ac34e2e..0f9428c 100644 --- a/myfavstuff/app/add-item/page.js +++ b/myfavstuff/app/add-item/page.js @@ -98,13 +98,13 @@ export default function AddItemPage() {
- +