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).
Guard request query params before coercing to Number
Don't pass request query values straight into Number(); undefined becomes NaN and slips past the type check.
Bad example
| 1 | function handler(req, res) { |
| 2 | // req.query.page is string | string[] | undefined |
| 3 | const page = Number(req.query.page); |
| 4 | const limit = Number(req.query.limit); |
| 5 | // Number(undefined) === NaN, but it is typed as `number`, |
| 6 | // so the type check passes and NaN flows downstream. |
| 7 | return fetchItems({ page, limit }); |
| 8 | } |
Explanation (EN)
Number(undefined) evaluates to NaN, and TypeScript still types the result as number, so the bad value silently slips through and corrupts pagination or any downstream math.
Objašnjenje (HR)
Number(undefined) daje NaN, a TypeScript ga i dalje tipizira kao number, pa neispravna vrijednost tiho prolazi i kvari paginaciju ili bilo koji izračun nizvodno.
Good example
| 1 | function handler(req, res) { |
| 2 | const { page, limit } = req.query; |
| 3 | // Guard before converting: only coerce when a value is present. |
| 4 | const parsedPage = page ? Number(page) : undefined; |
| 5 | const parsedLimit = limit ? Number(limit) : undefined; |
| 6 | return fetchItems({ page: parsedPage, limit: parsedLimit }); |
| 7 | } |
Explanation (EN)
Checking the raw value before calling Number() keeps undefined as undefined instead of NaN, so callers can apply real defaults and the type reflects reality.
Objašnjenje (HR)
Provjera sirove vrijednosti prije poziva Number() zadržava undefined kao undefined umjesto NaN, pa pozivatelji mogu primijeniti prave zadane vrijednosti i tip odgovara stvarnom stanju.
Notes (EN)
Prefer a small parse helper (parsePositiveInteger / validatePaginationQuery) that returns undefined or throws on invalid input, rather than scattering ternaries. Validate at the boundary so the rest of the code can trust the values.
Bilješke (HR)
Radije koristi mali helper za parsiranje (parsePositiveInteger / validatePaginationQuery) koji vraća undefined ili baca grešku na neispravan ulaz, umjesto razasutih ternarnih izraza. Validiraj na granici kako bi ostatak koda mogao vjerovati vrijednostima.