concept DataLoader in category graphql

This is an excerpt from Manning's book GraphQL in Action.
As the name implies, DataLoader is a utility you can use to read data from databases and make it available to GraphQL resolver functions. You can use DataLoader instead of reading the data directly from databases with SQL queries and DataLoader will act as your agent to reduce the SQL queries you send to the database.
Figure 1.6. DataLoader can optimize the requests between GraphQL and databases
![]()
DataLoader uses a combination of batching and caching to accomplish that. If the same client request resulted in a need to ask the database about multiple things, DataLoader can be used to consolidate these questions and batch-load their answers from the database. DataLoader will also cache the answers and make them available for subsequent questions about the same resources.
To use DataLoader in the AZdev API project, we need to install it first:
Listing 7.3. Command: Install the "dataloader" package
$ npm install dataloaderThis npm package has a default export which we usually import as
DataLoader. This default export is a JavaScript class that we can use to instantiate a DataLoader instance. TheDataLoaderclass constructor expects a function as its argument and that function is expected to do the data fetching. This function is known as the batch loading function because it expects an array of key IDs and it should fetch all records associated with these IDs in one batch action and then return these records as an array that has the same order as the array of input IDs.
Another reason to use a loader for this case is for consistency. DataLoader is now an abstraction layer in our stack and all database communication should happen through it. Mixing some direct database communication here would be a code smell.