import { json } from '@sveltejs/kit'; import { db } from '$lib/server/db'; import * as schema from '$lib/server/db/schema'; import { randomUUID } from 'crypto'; import { eq, and } from 'drizzle-orm'; export async function GET({ locals, url }) { if (!locals.user) { return json({ error: 'Unauthorized' }, { status: 401 }); } const userId = locals.user.id; const id = url.searchParams.get('id'); if (id) { const experiment = await db.query.experiment.findFirst({ where: (exp, { eq }) => eq(exp.id, id) }); if (!experiment) { return json({ error: 'Not found' }, { status: 404 }); } return json({ experiment }); } const experiments = await db.select().from(schema.experiment).where(eq(schema.experiment.createdBy, userId)); return json({ experiments }); } export async function POST({ request, locals }) { if (!locals.user) { return json({ error: 'Unauthorized' }, { status: 401 }); } const { name, description, multiplayer, type } = await request.json(); if (!name) { return json({ error: 'Name is required' }, { status: 400 }); } if (!type || !['jsPsych', 'PsychoJS'].includes(type)) { return json({ error: 'Invalid type' }, { status: 400 }); } const experiment = { id: randomUUID(), name, description, createdBy: locals.user.id, createdAt: new Date(), multiplayer: multiplayer || false, type }; await db.insert(schema.experiment).values(experiment); return json({ experiment }); } export async function PUT({ request, locals, url }) { if (!locals.user) { return json({ error: 'Unauthorized' }, { status: 401 }); } const id = url.searchParams.get('id'); if (!id) { return json({ error: 'Missing id' }, { status: 400 }); } const { name, description } = await request.json(); if (!name) { return json({ error: 'Name is required' }, { status: 400 }); } const [updated] = await db .update(schema.experiment) .set({ name, description }) .where(and(eq(schema.experiment.id, id), eq(schema.experiment.createdBy, locals.user.id))) .returning(); if (!updated) { return json({ error: 'Not found or not authorized' }, { status: 404 }); } return json({ experiment: updated }); }