Files
electric-cherry/src/routes/api/betas/presets/+server.ts
T

33 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { json } from '@sveltejs/kit';
import { db } from '$lib/server/db/index.js';
import { builtInPlans, parseBetaPlan } from '$lib/beta-plan.js';
export function GET() {
const saved = db()
.prepare('SELECT name, plan FROM beta_test_presets ORDER BY name')
.all() as Array<{ name: string; plan: string }>;
return json({
presets: [
...builtInPlans,
...saved.map((p) => ({ name: p.name, plan: JSON.parse(p.plan) }))
]
});
}
export async function POST({ request }: { request: Request }) {
try {
const body = await request.json();
if (typeof body.name !== 'string' || !body.name.trim() || body.name.length > 80)
throw new Error('Preset name must be 1–80 characters');
if (builtInPlans.some((p) => p.name === body.name.trim()))
throw new Error('Choose a name other than a built-in preset');
const plan = parseBetaPlan(body.plan);
db()
.prepare(
'INSERT INTO beta_test_presets (name, plan) VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET plan = excluded.plan'
)
.run(body.name.trim(), JSON.stringify(plan));
return json({ ok: true });
} catch (error) {
return json({ ok: false, error: (error as Error).message }, { status: 400 });
}
}