Tuesday, May 28, 2019

Using DataLoader in GraphQL

In my previous post, we created a GraphQL API for student application. In this post, we are going to improve that API and add DataLoader functionality into GraphQL API.
In the API, you will get a following result for the below query. Therefore, we should do an improvement relates to fetching course registration query.
First, we will add merge.js file below. Then we should modify, courseRegistration.js file.
Now, you can query the API again like below and you will see the result.
However, the above implementation contains a huge performance issue. That is, there are situations, that we are fetching the same student and/or course record multiple times. As it is still a small API, you will not see a huge performance issue, but when the API becomes larger, these repetitive & costly database calls should not be there. Therefore, we are going to use DataLoader.
DataLoader will coalesce all individual loads which occur within a single frame of execution (a single tick of the event loop) and then call your batch function with all requested keys.
First, we should install the node module dependency. Then, we can change the merge.js file like below.
You can download the source code for this application from GitHub.

No comments:

Post a Comment