Fetching Many Items by Key with GraphQL DataLoaders

Jacob Paris
InstructorJacob Paris
Share this video with your friends

Social Share Links

Send Tweet

One-to-many relationships are a prime candidate for scaling issues. In this lesson we'll add a new loader to fetch all the comments for a given post ID.

Instructor: [0:01] Let's add a new loader to fetch all of the comments for a given post ID. Select All from comments, where post ID is in the keys. Then we want to replace each key, each post ID, with an array of all the comments for that post.

[0:23] Under the post resolvers, add one for comments, which uses the new comments by post idLoader. Return comments by post idLoader.load post ID.

[0:35] Next, we'll add the comments field to the post schema, which returns an array of comments, and then the comment type, which has an ID, text, and an author field. We'll also need to resolve the author field on the comment type which we can just copy paste from the post type.

[0:52] Let's try querying the posts. We'll get all their comments and each ID, text, author ID, and name. No comments for the first few, looks like five comments on this one. Two comments here. All the information is right where it's supposed to be.