[SOLVED] Sending unnecessary data in one query response or making multiple queries?

Issue

I have been working on a project. I always followed this idea. Don’t send all the data in one call.

Here is an example,

Suppose there is an API to return all the list of students that can be added to test they need to finish.

So, on UI side every student have one button "add" which will show a pop up if the student is already assigned to take the test. Or it will show a pop up he has already finished the test.

I could join many table and send all the data in one api call while fetchig students. Or
I could send the send the students and then on "add" there is another API to make sure the above mentioned conditioned met.

Which approach is better?

Because If I send all the data in one api call, there might be only few students be assigned the test.

Solution

Checking if a student is already assigned or not should happen in the backend, not frontend, and also atomically so as to prevent duplicates – either using a database transaction or a unique constraint.

When the Add button is clicked then in any case a backend call will need to be made (to perform the actual Add). If the add failed, the backend can interpret the "unique constraint violation" database error and return a "student is already assigned" message.

For the rest of the question, the rule is simply: don’t fetch more data than is required by the UI.

If the Add button is always shown regardless of whether or not the student is already added, there is no need to retrieve this information beforehand.

But it might be useful to give a visual indication of which students are already added, in that case obviously there’s no choice but to retrieve and return this information to the UI.

Fortunately GraphQL is precisely the tool for this job – it makes it possible for the UI to request exactly what information is needed for a given page, without having to code each and every possible query by hand.

Answered By – rustyx

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *