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).
Avoid N+1 queries with batching or preloading
Batch related data fetching to prevent N+1 query patterns.
Bad example
| 1 | export async function listPosts() { |
| 2 | const posts = await db.post.findMany(); |
| 3 |
|
| 4 | const result = []; |
| 5 | for (const post of posts) { |
| 6 | const author = await db.user.findById(post.authorId); |
| 7 | result.push({ ...post, author }); |
| 8 | } |
| 9 |
|
| 10 | return result; |
| 11 | } |
Explanation (EN)
This executes one query for posts plus one query per post (N+1), which is slow and expensive at scale.
Objašnjenje (HR)
Ovo izvrsava jedan upit za postove plus jedan upit po postu (N+1), sto je sporo i skupo na velikoj skali.
Good example
| 1 | export async function listPosts() { |
| 2 | return db.post.findMany({ |
| 3 | include: { author: true }, |
| 4 | }); |
| 5 | } |
Explanation (EN)
Batching or preloading fetches related data in one query and avoids N+1 round trips.
Objašnjenje (HR)
Batchiranje ili preloading dovlaci povezane podatke u jednom upitu i izbjegava N+1 pozive.
Exceptions / Tradeoffs (EN)
Small, bounded lists may be acceptable, but measure and document the tradeoff.
Iznimke / Tradeoffi (HR)
Male, ogranicene liste mogu biti prihvatljive, ali izmjeri i dokumentiraj kompromis.