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 repeated API guard logic into middleware
Move duplicated method checks, auth/session guards, and error formatting out of individual handlers into shared middleware or a wrapper.
Bad example
| 1 | // Repeated in every handler |
| 2 | const handlerA = async (req, res) => { |
| 3 | if (req.method !== 'POST') return res.status(405).json({ message: 'Method not allowed' }); |
| 4 | if (!req.cookies.session) return res.status(401).json({ message: 'Unauthorized' }); |
| 5 | // ... |
| 6 | }; |
| 7 | const handlerB = async (req, res) => { |
| 8 | if (req.method !== 'POST') return res.status(405).json({ message: 'Method not allowed' }); |
| 9 | if (!req.cookies.session) return res.status(401).json({ message: 'Unauthorized' }); |
| 10 | // ... |
| 11 | }; |
Explanation (EN)
The same method and auth guards are copy-pasted into every handler. Any change (status code, message shape, cookie name) must be made in many places and drifts out of sync.
Objašnjenje (HR)
Iste provjere metode i autentikacije su kopirane u svaki handler. Svaka promjena (status kod, oblik poruke, ime cookieja) mora se napraviti na puno mjesta i s vremenom se razilazi.
Good example
| 1 | const withGuards = (handler, { method }) => async (req, res) => { |
| 2 | if (req.method !== method) return res.status(405).json({ message: 'Method not allowed' }); |
| 3 | if (!req.cookies.session) return res.status(401).json({ message: 'Unauthorized' }); |
| 4 | return handler(req, res); |
| 5 | }; |
| 6 |
|
| 7 | const handlerA = withGuards(async (req, res) => { |
| 8 | // ... business logic only |
| 9 | }, { method: 'POST' }); |
Explanation (EN)
Cross-cutting guards live in one wrapper. Handlers contain only business logic, and changes to auth or error shape happen in a single place.
Objašnjenje (HR)
Zajednicke provjere su u jednom wrapperu. Handleri sadrze samo poslovnu logiku, a promjene autentikacije ili oblika greske rade se na jednom mjestu.
Exceptions / Tradeoffs (EN)
A one-off handler with genuinely unique guard logic does not need to be forced into the shared abstraction.
Iznimke / Tradeoffi (HR)
Jednokratni handler sa stvarno jedinstvenom logikom provjere ne mora se na silu uklapati u zajednicku apstrakciju.