Refactor the Data Loader into a Reusable Class

Jacob Paris
InstructorJacob Paris
Share this video with your friends

Social Share Links

Send Tweet
Published 2 years ago
Updated 2 years ago

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.

egghead
egghead
~ 2 hours ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today