import Elysia, { NotFoundError, t } from "elysia"; import { StandardsParamsSchema } from "@blade-and-brawn/calculator"; import { authPlugin } from "../plugins/auth"; import { s } from "../services"; import { BigIntIdSchema } from "../util/models"; import { ConflictError } from "../util/error"; const StandardsController = new Elysia({ prefix: "/standards" }) .use(authPlugin) .group("/configs", { authAdmin: true }, (app) => app .post("/", async ({ body: { name, datasetId, params } }) => { return await s.Standards.Configs.create(name, datasetId, params); }, { body: t.Object({ name: t.String(), datasetId: BigIntIdSchema, params: StandardsParamsSchema }) }) .get("/", async () => { return await s.Standards.Configs.list(); }) .group("/:id", (app) => app .get("/", async ({ params: { id } }) => { const config = await s.Standards.Configs.get(id); if (!config) throw new NotFoundError("Standards config not found"); return config; }, { params: t.Object({ id: BigIntIdSchema }) }) .put("/", async ({ params: { id }, body: { name, datasetId, params: parameters } }) => { // Active config is not allowed to be edited const activeConfig = await s.Calculator.Standards.Config.get(); if (activeConfig.id === id) throw new ConflictError("Cannot edit the active standards config"); const updated = await s.Standards.Configs.update(id, name, datasetId, parameters); if (!updated) throw new NotFoundError("Standards config not found"); }, { params: t.Object({ id: BigIntIdSchema }), body: t.Object({ name: t.String(), datasetId: BigIntIdSchema, params: StandardsParamsSchema }) }) .delete("/", async ({ params: { id } }) => { if (await s.Standards.Configs.count() <= 1) throw new ConflictError("Cannot delete the last remaining standards config"); const deleted = await s.Standards.Configs.delete(id); if (!deleted) throw new NotFoundError("Standards config not found"); }, { params: t.Object({ id: BigIntIdSchema }) }) ) ) .group("/datasets", { authAdmin: true }, (app) => app .get("/", async () => { return await s.Standards.Datasets.list(); }) .group("/:id", (app) => app .get("/", async ({ params: { id } }) => { const dataset = await s.Standards.Datasets.get(id); if (!dataset) throw new NotFoundError("Standards dataset not found"); return dataset; }, { params: t.Object({ id: BigIntIdSchema }) }) .patch("/", async ({ params: { id }, body: { name } }) => { const updated = await s.Standards.Datasets.update(id, name); if (!updated) throw new NotFoundError("Standards dataset not found"); }, { params: t.Object({ id: BigIntIdSchema }), body: t.Object({ name: t.String() }) }) ) ); export default StandardsController;