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).
Validate or default required connection config before building a connection string
Interpolating possibly-undefined env vars into a connection string yields 'undefined' segments and cryptic connect failures. Validate required values (or provide explicit defaults) first.
Bad example
| 1 | // If REDIS_HOST is unset this becomes redis://...@undefined:6379 |
| 2 | const url = `redis://${process.env.REDIS_USERNAME}:${process.env.REDIS_PASSWORD}@${process.env.REDIS_HOST}:${Number(process.env.REDIS_PORT) || 6379}`; |
| 3 | connect(url); |
Explanation (EN)
A missing env var stringifies to 'undefined' inside the template, producing an invalid URL and an opaque connection error far from the real cause.
Objašnjenje (HR)
Env varijabla koja nedostaje pretvara se u 'undefined' unutar predloska, sto daje nevazeci URL i nejasnu gresku spajanja daleko od pravog uzroka.
Good example
| 1 | const required = ['REDIS_HOST', 'REDIS_PORT'] as const; |
| 2 | const missing = required.filter((k) => !process.env[k]); |
| 3 | if (missing.length) { |
| 4 | throw new Error(`Missing required config: ${missing.join(', ')}`); |
| 5 | } |
| 6 |
|
| 7 | const host = process.env.REDIS_HOST; |
| 8 | const port = Number(process.env.REDIS_PORT) || 6379; |
| 9 | const url = `redis://${host}:${port}`; |
Explanation (EN)
Checking required values up front fails fast with a clear message naming the missing key, and applying explicit defaults guarantees the connection string is always well-formed.
Objašnjenje (HR)
Provjera obaveznih vrijednosti unaprijed pada brzo s jasnom porukom koja imenuje kljuc koji nedostaje, a primjena eksplicitnih zadanih vrijednosti jamci da je connection string uvijek ispravno oblikovan.
Exceptions / Tradeoffs (EN)
If a centralized env-validation step already asserts these variables at startup, re-checking at the call site is redundant.
Iznimke / Tradeoffi (HR)
Ako centralizirani korak validacije env varijabli vec provjerava ove varijable pri pokretanju, ponovna provjera na mjestu poziva je suvisna.