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 write an unserializable value into a cache, and treat it as a miss on read
Serializing undefined yields undefined rather than a string, so the write stores garbage and every later read throws while parsing it - poisoning that key until the process restarts. Skip the write when the value is absent, and treat an absent stored value as a miss.
Bad example
| 1 | set(key, value, ttl) { |
| 2 | // JSON.stringify(undefined) === undefined, not a string |
| 3 | return client.setEx(key, ttl, JSON.stringify(value)); |
| 4 | } |
| 5 |
|
| 6 | async get(key) { |
| 7 | const raw = await client.get(key); |
| 8 | return raw !== null ? JSON.parse(raw) : null; // JSON.parse(undefined) throws forever |
| 9 | } |
Explanation (EN)
An absent value is written as a non-string, and the read path only guards null, so the key throws on every subsequent read.
Objašnjenje (HR)
Vrijednost koja ne postoji zapisuje se kao ne-string, a citanje provjerava samo null, pa taj kljuc puca na svakom sljedecem citanju.
Good example
| 1 | set(key, value, ttl) { |
| 2 | if (value === undefined) return; // not cacheable |
| 3 | return client.setEx(key, ttl, JSON.stringify(value)); |
| 4 | } |
| 5 |
|
| 6 | async get(key) { |
| 7 | const raw = await client.get(key); |
| 8 | if (raw === null || raw === undefined) return null; // both are a miss |
| 9 | return JSON.parse(raw); |
| 10 | } |
Explanation (EN)
Non-cacheable values are returned to the caller but never stored, and both absent forms read as a miss.
Objašnjenje (HR)
Vrijednosti koje se ne mogu kesirati vracaju se pozivatelju, ali se nikad ne spremaju, a oba oblika odsutnosti citaju se kao promasaj.
Notes (EN)
Cache libraries usually have this guard built in. If you replace one with your own layer, port the guard too - the failure only shows up on the second request for the key.
Bilješke (HR)
Biblioteke za kesiranje obicno vec imaju tu zastitu. Ako takvu biblioteku zamijenis vlastitim slojem, prenesi i zastitu - kvar se vidi tek na drugom zahtjevu za isti kljuc.