Optimizing backends using GraphQL
GraphQL effectively eliminates transfer of redundant data when using APIs. It is also possible to prevent over-fetching data from a database. In order to do that, we need to extract fields coming from GraphQL and dynamically build a query.
I am going to extend the source code used in my first post Using GraphQL in .NET ecosystem to show how you can achieve it in .NET environment.
In order to extract query fields, we are going to use IResolveFieldContext<object> which is provided as a parameter in the query resolver.
The extracted fields would be in a JSON format as they appear in playground (playerId, firstName). I’ve created an extension method to capitalize them, so they match the column names in our database table. Shortly we’re going to construct dynamic query using these fields.
Now we’re going to extend our repository files to handle dynamic queries.
I’ve extracted all the heavy work into an extension method DynamicSqlQuery, which is generic and can be reused with other repositories as well.
Here we fetch from database only the fields that we’re interested in and dynamically create an instance of our generic type which will be eventually returned to a client.
Finally, I am using SQL Server Profiler to see what’s happening on database level. You can clearly see that we’re getting only the fields that our GraphQL query requested.
Summary
This post demonstrates how you can optimize backends by reducing cost of SQL queries using GraphQL.