SERVER ~ JANUARY 09 2023
I have fallen for GraphQL in a big way and I would like to try to explain why as it might help explain the benefits to many folk who simply pass it by and continue to struggle to manage their data flow in their applications, React especially (you can use GraphQL in many different contexts, React is just one).
To start with I'll focus on a data fetching method in plain Javascript which is a typical method for getting data in Front Ends. Developers, I've often found, will fire many independant fetch requests throughout their app and at various points within their applications, often to various places using a straight fetch
request or some package or other like axios
. Here is a typical fetch request with a few extra elements you can commonly find added after fetching.
So what is happening here exactly? In this particular instance I am using a third party API to get ip address information under the data
variable. What follows that is a conversion using the built in json
function to convert the result. After this it is very common to find a developer needing to somehow sanitise their data or aggregate it in some way. Here, I have renamed a few fields, gathered the results I want into one object. I've also time stamped the object and added a conditional return.
That isn't the end of the story, this data then needs to be broadcast to an internal server which will take the data and internally add it to a database, to be recalled by another part of the application (probably using another fetch request).
Now compare that to this.
Of course I'm not saying all that previous code goes away, however, it gets essentially moved back to the server side, allowing the Front End to do what it was meant to do which is deal with display and interaction.
What you are essentially doing here is funneling all your data interaction through one place, usually a server of some kind with a /graphql
endpoint as a convention. Once that link has been made through a package such as Apollo Client, everything else is handled and interaction with your data including extras like caching, integrate seamlessly into the developer workflow.
The above two pieces of code are known as a mutation
(the top one) and a query
. These are the two main interfaces between the Front End application and the GraphQL server. The other great benefit of GraphQL is the ability to ask for as much or as little data as you need for your Front End, so potentially you can optimise data fetching without even thinking about it. Your query could consist of two or more data fetches and your server only needs to perform one of them to get less of the data. You automatically speed up your application as a result.