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>
This commit is contained in:
@@ -3,6 +3,7 @@ import { join } from "node:path";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { Hono } from "hono";
|
||||
import { createItemSchema, updateItemSchema } from "../../shared/schemas.ts";
|
||||
import { parseId } from "../lib/params.ts";
|
||||
import {
|
||||
createItem,
|
||||
deleteItem,
|
||||
@@ -23,7 +24,8 @@ app.get("/", (c) => {
|
||||
|
||||
app.get("/:id", (c) => {
|
||||
const db = c.get("db");
|
||||
const id = Number(c.req.param("id"));
|
||||
const id = parseId(c.req.param("id"));
|
||||
if (!id) return c.json({ error: "Invalid item ID" }, 400);
|
||||
const item = getItemById(db, id);
|
||||
if (!item) return c.json({ error: "Item not found" }, 404);
|
||||
return c.json(item);
|
||||
@@ -41,7 +43,8 @@ app.put(
|
||||
zValidator("json", updateItemSchema.omit({ id: true })),
|
||||
(c) => {
|
||||
const db = c.get("db");
|
||||
const id = Number(c.req.param("id"));
|
||||
const id = parseId(c.req.param("id"));
|
||||
if (!id) return c.json({ error: "Invalid item ID" }, 400);
|
||||
const data = c.req.valid("json");
|
||||
const item = updateItem(db, id, data);
|
||||
if (!item) return c.json({ error: "Item not found" }, 404);
|
||||
@@ -51,7 +54,8 @@ app.put(
|
||||
|
||||
app.delete("/:id", async (c) => {
|
||||
const db = c.get("db");
|
||||
const id = Number(c.req.param("id"));
|
||||
const id = parseId(c.req.param("id"));
|
||||
if (!id) return c.json({ error: "Invalid item ID" }, 400);
|
||||
const deleted = deleteItem(db, id);
|
||||
if (!deleted) return c.json({ error: "Item not found" }, 404);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user