Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Never cast req.query to a typed interface — parse and clamp each field explicitly
Express always hands query params to you as string | string[] | undefined regardless of what interface you cast req.query to. Explicitly parse each numeric param (e.g. parseInt with a fallback) and clamp both the lower and upper bound — don't rely on `??` alone, since an empty string is not undefined/null and slips right past it.
Bad example
| 1 | interface IQueryParams { limit?: number; offset?: number; } |
| 2 |
|
| 3 | const { limit, offset } = req.query as IQueryParams; |
| 4 | const pageLimit = Math.min(limit ?? 10, 100); |
Explanation (EN)
The cast lies about the runtime type. `?limit=abc` becomes NaN and slips past a `> maxWindow` guard; `?limit=` (empty string) skips the `??` fallback entirely, since `''` is neither null nor undefined.
Objašnjenje (HR)
Cast laže o stvarnom runtime tipu. `?limit=abc` postaje NaN i prolazi kroz `> maxWindow` provjeru; `?limit=` (prazan string) potpuno zaobilazi `??` fallback jer `''` nije ni null ni undefined.
Good example
| 1 | const limit = Math.min(parseInt(String(req.query.limit ?? ''), 10) || 10, 100); |
| 2 | const offset = Math.max(0, parseInt(String(req.query.offset ?? ''), 10) || 0); |
Explanation (EN)
Explicit parseInt with a fallback and both-bound clamping handles the NaN, empty-string, and negative-offset cases correctly, regardless of what shape the query string actually arrives in.
Objašnjenje (HR)
Eksplicitni parseInt s fallbackom i ograničavanjem obje granice ispravno rješava slučajeve NaN, praznog stringa i negativnog offseta, bez obzira na stvarni oblik query stringa.