36 lines
1.6 KiB
TypeScript
36 lines
1.6 KiB
TypeScript
import { PUBLIC_SUPABASE_ANON_KEY, PUBLIC_SUPABASE_URL } from "$env/static/public";
|
|
import type { Database } from "$lib/database";
|
|
import { createClient } from "@supabase/supabase-js";
|
|
import { error, type RequestHandler } from "@sveltejs/kit";
|
|
|
|
export const POST: RequestHandler = async ({ request }) => {
|
|
const supabase = createClient<Database>(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY);
|
|
const body = await request.bytes();
|
|
const url = new URL(request.url);
|
|
const title = url.searchParams.get("title");
|
|
const imgTitle = url.searchParams.get("imgTitle");
|
|
if (!title || !imgTitle) error(400, "Missing required fields: title, imgTitle");
|
|
|
|
const { data: imageData, error: imageError } = await supabase.storage
|
|
.from("files_bucket")
|
|
.upload(`public/${imgTitle}`, body, {
|
|
contentType: request.headers.get("content-type") || "image/png",
|
|
upsert: false
|
|
});
|
|
if (imageError) error(500, `Failed to upload image: ${imageError.message}`);
|
|
|
|
const { data: studySpaceData, error: studySpaceError } = await supabase
|
|
.from("study_spaces")
|
|
.insert({ title })
|
|
.select()
|
|
.single();
|
|
if (studySpaceError) error(500, "Failed to create study space");
|
|
|
|
const { error: imageLinkError } = await supabase
|
|
.from("study_space_images")
|
|
.insert({ study_space_id: studySpaceData.id, image_path: imageData.path });
|
|
|
|
if (imageLinkError) error(500, "Failed to link image to study space");
|
|
return new Response(JSON.stringify({ id: studySpaceData.id }), { status: 200 });
|
|
};
|