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

35 lines
1.2 KiB
TypeScript

import { json } from '@sveltejs/kit';
import {
RebalanceError,
previewRebalance,
rebalanceReport,
startRebalance,
stopRebalance
} from '$lib/server/rebalancing/index.js';
export function GET() {
return json(rebalanceReport());
}
export async function POST({ request }: { request: Request }) {
try {
const body = await request.json();
if (!body || typeof body !== 'object' || Array.isArray(body))
throw new RebalanceError('Provide a rebalance action.');
if (body.action === 'preview') return json({ preview: previewRebalance(body.settings) });
if (
body.action === 'start' &&
typeof body.previewId === 'string' &&
body.previewId.length <= 100
)
return json({ run: startRebalance(body.previewId) });
if (body.action === 'stop' && typeof body.id === 'string' && body.id.length <= 100)
return json({ run: stopRebalance(body.id) });
throw new RebalanceError('Choose a supported rebalance action.');
} catch (error) {
return json(
{ error: (error as Error).message },
{ status: error instanceof RebalanceError ? error.status : 400 }
);
}
}