Files
GearBox/src/server/routes/categories.ts
Jean-Luc Makiola ecff58500e fix: validate route ID parameters, return 400 for invalid IDs
Adds parseId helper in src/server/lib/params.ts and applies it across
all route files so non-positive-integer IDs return 400 instead of
silently passing NaN to services.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 15:34:06 +02:00

63 lines
1.5 KiB
TypeScript

import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import {
createCategorySchema,
updateCategorySchema,
} from "../../shared/schemas.ts";
import { parseId } from "../lib/params.ts";
import {
createCategory,
deleteCategory,
getAllCategories,
updateCategory,
} from "../services/category.service.ts";
type Env = { Variables: { db?: any } };
const app = new Hono<Env>();
app.get("/", (c) => {
const db = c.get("db");
const cats = getAllCategories(db);
return c.json(cats);
});
app.post("/", zValidator("json", createCategorySchema), (c) => {
const db = c.get("db");
const data = c.req.valid("json");
const cat = createCategory(db, data);
return c.json(cat, 201);
});
app.put(
"/:id",
zValidator("json", updateCategorySchema.omit({ id: true })),
(c) => {
const db = c.get("db");
const id = parseId(c.req.param("id"));
if (!id) return c.json({ error: "Invalid category ID" }, 400);
const data = c.req.valid("json");
const cat = updateCategory(db, id, data);
if (!cat) return c.json({ error: "Category not found" }, 404);
return c.json(cat);
},
);
app.delete("/:id", (c) => {
const db = c.get("db");
const id = parseId(c.req.param("id"));
if (!id) return c.json({ error: "Invalid category ID" }, 400);
const result = deleteCategory(db, id);
if (!result.success) {
if (result.error === "Cannot delete the Uncategorized category") {
return c.json({ error: result.error }, 400);
}
return c.json({ error: result.error }, 404);
}
return c.json({ success: true });
});
export { app as categoryRoutes };