This video is available to students only

Modularizing Resolvers

In this lesson, we'll see how we can use the lodash merge function to have our GraphQL resolvers map be broken down to small resolvers objects that pertain to certain domains (i.e modules).

📝 This lesson's quiz can be found - here. 🗒️ Solutions for this lesson's quiz can be found - here.

If our app was to continue to grow, our resolvers.ts file will continue to get bigger to accommodate all the different resolvers within the different object types in our API. Though there's nothing inherently wrong with this, we can look to separate our resolvers into different resolvers maps (i.e. modules) in such a way that each resolvers map will pertain a particular domain (or module).

For example, assume we had a resolvers map just for resolvers that pertain to the listings domain (i.e. the listingResolvers). The listings resolvers map will encompass all the resolvers that pertain to the listing domain or module such as the listings query, the deleteListing mutation, the id resolver field for the Listing object, etc.

We could have another resolvers map that deals with a different domain or module. For example, we can have a userResolvers map that contained all the resolvers that pertain to retrieving or changing user data in our database.

This level of modularization will make no change to the actual functionality of our app but aim to have our resolvers be more concise and easier to read.

Let's set up the resolvers of our API to follow this level of modularization. The first thing we'll do is create a new folder called resolvers in our src/graphql/ folder. The src/graphql/resolvers/ folder is where we'll place each of our different resolvers objects.

In the src/graphql/resolvers/ folder, we'll create a sub-folder for each module we'd want to have a resolvers object. At this moment in time, we only have the capability to modify and read data about listings (i.e. we only have a listings collection), so we'll create a Listing/ sub-folder that contains an index.ts file where we'll create and export a listingResolvers map.

We'll move everything from our src/graphql/resolvers.ts file to the index.ts file in src/graphql/resolvers/Listing/ and rename the exported resolvers object to listingResolvers.

Start a new discussion. All notification go to the author.