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).
Extract duplicated API route validators into shared utilities
When the same request parsing or validation helper appears in multiple routes with the same behavior, move it to a shared utility.
Bad example
| 1 | const parsePositiveInteger = (value: string | string[] | undefined) => { |
| 2 | if (!value || Array.isArray(value)) return null; |
| 3 | const parsedValue = Number(value); |
| 4 | if (!Number.isInteger(parsedValue) || parsedValue <= 0) return null; |
| 5 | return parsedValue; |
| 6 | }; |
| 7 |
|
| 8 | const getValidatedAuthToken = (authToken: string | string[] | undefined) => { |
| 9 | if (!authToken) return { error: { message: 'Unauthorized: Missing auth token.', statusCode: 401 } }; |
| 10 | if (typeof authToken !== 'string') return { error: { message: 'Bad token.', statusCode: 400 } }; |
| 11 | return { authToken }; |
| 12 | }; |
Explanation (EN)
Copying identical validators across route files makes maintenance harder and increases the chance of inconsistent behavior later.
Objašnjenje (HR)
Kopiranje identicnih validatora po route fileovima otezuje odrzavanje i povecava sansu za nekonzistentno ponasanje kasnije.
Good example
| 1 | import { parsePositiveInteger } from 'utils/api/parsePositiveInteger'; |
| 2 | import { getValidatedAuthToken } from 'utils/api/getValidatedAuthToken'; |
| 3 | import { getValidatedPortfolioId } from 'utils/api/getValidatedPortfolioId'; |
| 4 |
|
| 5 | const portfolioIdResult = getValidatedPortfolioId(req.query.id); |
| 6 | const authTokenResult = getValidatedAuthToken(req.headers['x-auth-token']); |
Explanation (EN)
The shared utilities keep route behavior consistent and reduce boilerplate. Changes to validation logic only need to happen in one place.
Objašnjenje (HR)
Shared utilityji drze ponasanje routeova konzistentnim i smanjuju boilerplate. Promjene validacije rade se na jednom mjestu.
Notes (EN)
A good trigger is 3 or more identical copies in the same feature or route group.
Bilješke (HR)
Dobar trigger je 3 ili vise identicnih kopija unutar istog featurea ili route grupe.
Exceptions / Tradeoffs (EN)
Keep a validator local if the behavior is intentionally route-specific or the shared version would become too generic to understand.
Iznimke / Tradeoffi (HR)
Validator ostaje lokalno ako je ponasanje namjerno route-specific ili bi shared verzija postala previse genericka za razumjeti.