mirror of
https://github.com/Studio-Saelix/sencho.git
synced 2026-08-10 10:49:35 +00:00
refactor(backend): hoist parseIntParam helper to utils (#798)
Adds backend/src/utils/parseIntParam.ts with a shared parseIntParam helper that writes a 400 'Invalid <label>' response and returns null on non-numeric route params. Consolidates the parseInt + isNaN + 400 shape that was inlined or duplicated across multiple routers. Updated: - routes/fleet.ts: replaced the local parseIdParam wrapper. - routes/autoHeal.ts: replaced the local parsePolicyId wrapper. - routes/notifications.ts: replaced parseRouteId wrapper plus an inline notification-id site. - routes/apiTokens.ts, routes/labels.ts, routes/registries.ts, routes/scheduledTasks.ts, routes/users.ts: replaced inline copies. Out of scope (route handlers without an existing isNaN check, kept intentionally untouched to avoid introducing new 400 responses): alerts, nodes, webhooks, and several user-routes handlers that rely on a downstream 404 instead. Closes #748
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
import type { Request, Response } from 'express';
|
||||
|
||||
/**
|
||||
* Parse a numeric route param. Writes a 400 response and returns null when
|
||||
* the value isn't a valid integer; callers early-return on null.
|
||||
*
|
||||
* @param paramName the key in req.params (e.g. 'id', 'nodeId')
|
||||
* @param label optional human-readable label used in the error body.
|
||||
* Falls back to paramName when omitted (e.g. 'Invalid id').
|
||||
*/
|
||||
export function parseIntParam(
|
||||
req: Request,
|
||||
res: Response,
|
||||
paramName: string,
|
||||
label?: string,
|
||||
): number | null {
|
||||
const raw = req.params[paramName] as string | undefined;
|
||||
const parsed = parseInt(raw ?? '', 10);
|
||||
if (isNaN(parsed)) {
|
||||
res.status(400).json({ error: `Invalid ${label ?? paramName}` });
|
||||
return null;
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
Reference in New Issue
Block a user