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).
Handle pre-existing pooled resources when patching via a "new resource" event
A listener on a pool's "new connection/resource" event only fires for instances created *after* the listener is registered. Resources opened earlier (e.g. during startup migrations, before your bootstrap phase runs) must be patched explicitly — don't rely on a single one-off call happening to catch the only pre-existing instance.
Bad example
| 1 | pool.on('connection', (connection) => { |
| 2 | connection.query(UTC_SESSION_SQL); |
| 3 | }); |
| 4 | // migrations already opened one or more connections before this listener existed |
| 5 | await dataSource.query(UTC_SESSION_SQL); // patches only one connection back from the pool |
Explanation (EN)
If migrations (or any other startup step) ran before this listener attached, they may have opened more than one physical connection under the default pool size. The single `dataSource.query()` call only happens to patch whichever connection the pool hands back — any other pre-existing connection is silently left unpatched for its whole lifetime.
Objašnjenje (HR)
Ako su migracije (ili bilo koji drugi korak pri pokretanju) izvrsene prije nego se ovaj listener prikacio, mogle su otvoriti vise od jedne fizicke konekcije unutar zadane velicine poola. Jedan poziv `dataSource.query()` slucajno zakrpi samo konekciju koju pool vrati — svaka druga vec postojeca konekcija ostaje tiho nezakrpljena kroz cijeli svoj zivotni vijek.
Good example
| 1 | pool.on('connection', (connection) => { |
| 2 | connection.query(UTC_SESSION_SQL).on('error', (err) => logger.error(err)); |
| 3 | }); |
| 4 | // explicitly cover every connection already open before the listener attached |
| 5 | for (const connection of pool._allConnections ?? []) { |
| 6 | connection.query(UTC_SESSION_SQL).on('error', (err) => logger.error(err)); |
| 7 | } |
Explanation (EN)
Iterating every already-open connection at startup, in addition to the listener for future ones, guarantees full coverage instead of depending on how many connections happened to be pre-opened.
Objašnjenje (HR)
Iteriranje kroz svaku vec otvorenu konekciju pri pokretanju, uz listener za buduce, garantira potpunu pokrivenost umjesto oslanjanja na to koliko je konekcija slucajno vec otvoreno.
Notes (EN)
This race is easy to miss because it works in dev/test where usually exactly one connection is opened before bootstrap — it only surfaces under load or with a different pool/connectionLimit configuration.
Bilješke (HR)
Ovu utrku je lako previdjeti jer radi u dev/testu gdje se obicno tocno jedna konekcija otvori prije bootstrapa — pojavljuje se tek pod opterecenjem ili s drugacijom pool/connectionLimit konfiguracijom.