Refactor the Data Loader into a Reusable Class

Jacob Paris
InstructorJacob Paris
Share this video with your friends

Social Share Links

Send Tweet

We can make this data loader reusable by refactoring it into a class with configurable scheduling and batch functions

Instructor: [0:00] Hard coding the timeout to one millisecond batch sizes limits the flexibility of this API. We'll make a new method called scheduling function and copy the timeout logic from the load method there. We can replace the resolve with a return.

[0:21] We just have to await the scheduling function to put the timeout back into effect. The next tree factor is to extract the database operation into configurable batch function method. We can use this loader for more than just selecting users by ID.

[0:37] Let's stop here and make sure everything still works. One way to make the batch function configurable is to turn this into a class, so we can have a userLoader instance and a postLoader instance.

[0:50] The only difference is they pass different batch function parameters when we construct them with the DataLoader. Rename the cache to class DataLoader, and in the constructor, assign promises and active query as member variables. Set the batch function here too, from an argument to the constructor. Then the scheduling function is optional so we can hide that behind an options object.

[1:16] Throw an error not implemented, if there's no batch function. We can create userLoader as a new DataLoader. Pass in a batch function that takes keys, select all from users, where ID in keys. Replace the old cache.load call with user loader call and try it out.

[1:47] It's looking like everything still works and our refactor was successful.