Rules Hub
Coding Rules Library
Prefer declarative serialization for response shaping
Use a configuration-based serializer to handle edge cases (like omitting fields) instead of hardcoding conditional logic in controllers.
Bad example
| 1 | export async function GET(req: Request, { params }: { params: { year: string } }) { |
| 2 | const data = await getListData(params.year); |
| 3 |
|
| 4 | // BAD: Imperative, hardcoded logic for specific edge cases |
| 5 | // inside the controller makes it hard to track API contracts. |
| 6 | if (params.year === "2025" && data.funFacts) { |
| 7 | delete data.funFacts.numberOfBillionaires; |
| 8 | } |
| 9 |
|
| 10 | return NextResponse.json(data); |
| 11 | } |
Explanation (EN)
The controller contains ad-hoc imperative logic to mutate the response for specific cases. This mixes business rules with data retrieval and makes the API response shape unpredictable and harder to test.
Objašnjenje (HR)
Kontroler sadrži 'ad-hoc' imperativnu logiku za izmjenu odgovora u specifičnim slučajevima. Ovo miješa poslovna pravila s dohvaćanjem podataka i čini strukturu API odgovora nepredvidivom i težom za testiranje.
Good example
| 1 | const serializerConfig = { |
| 2 | "2025": { |
| 3 | omit: ["numberOfBillionaires"] |
| 4 | } |
| 5 | }; |
| 6 |
|
| 7 | export async function GET(req: Request, { params }: { params: { year: string } }) { |
| 8 | const data = await getListData(params.year); |
| 9 |
|
| 10 | // GOOD: Shaping rules are declarative and separated from the handler |
| 11 | const serializedData = serialize(data, serializerConfig[params.year]); |
| 12 |
|
| 13 | return NextResponse.json(serializedData); |
| 14 | } |
Explanation (EN)
Response shaping is abstracted into a declarative configuration (pick/omit/transform). The controller simply applies the serializer, keeping the code clean and the logic for exceptions centralized.
Objašnjenje (HR)
Oblikovanje odgovora je apstrahirano u deklarativnu konfiguraciju (pick/omit/transform). Kontroler samo primjenjuje serijalizator, čime kod ostaje čist, a logika za iznimke centralizirana.
Notes (EN)
Commonly used for handling backward compatibility or hiding specific fields (e.g., sensitive data or empty values) for certain resource versions.
Bilješke (HR)
Često se koristi za upravljanje kompatibilnošću unatrag ili skrivanje specifičnih polja (npr. osjetljivi podaci ili prazne vrijednosti) za određene verzije resursa.