✅ When should you or shouldnt you return nested data in an api call?
Let's say I have a these tables in my database, Project, Members, Task, Comments and I want to return paginated data so a user can view all their projects, then view the tasks and members associated with the project and the comments associated with the individual tasks. Would you do this as all separate queries or do one query that returns all the data nested and paginated?
Here's my current thought process.
3 Replies
It depends on what the frontend needs to display at that moment
Apis should be suited to the frontend
Or be one-size-fit-all
If you tailor them to the frontend, and you would display the first few comments always, include those few first comments
If you don't show comments, paginate them separately
the way you paginate should also depend on the needs of the frontend
Do this if you don't have a specific frontend
one-size-fit-all should either guess what the frontend would typically want, or only return a single thing
jus comments, just posts, etc
Perfect so this is what I'm trying to do, structure my apis to match the front end i already built out.
However my next question is if ur fetching the data from the database for something like a task and it's comments, should u get the single task and all of its comments and then loop over the comments up to say 5 and then send the 5 comments back in the json response to the client.
and then have a seperate end point thats just gonna keep fetching the paginated comments for that task
or instead do 2 separate api calls from the start, one for the task, and the other just getting the 5 comments for that task and then creating the json response object, and have them load independently on the front end, and then every time u wanna get the next page of comments u already have that getPaginatedComments endpoint to call
Nvm think I figured out the answer and I should use projections to go over the returned data and structuring it how I want before mapping it to a dto and sending it the client
Ideally you want to fetch everything in a single database roundtrip, project to a dto