Refactoring a Simple Node.js API

At least, it started off as the same function.

Besides the comments, I also re-implemented the function as an async (short for asynchronous) function due to the fact that I’m making an external API request that take a variable amount of time to complete.

I won’t go too in depth in async functions, but freeCodeCamp’s article on async/await is a great resource to learn more about it.

Another thing you might notice is that we’re missing the endpoint we see in the first line of Example 1.

Separating ConcernsThis takes us back to the third objective in this refactor process.

I was taught that files should be grouped based on functionality.

And while the initial implementation was passable, I didn’t quite feel satisfied with the results.

Here’s my refactored file structure:Compared to the initial file structure, we can see that there three more folders.

The only one we’re concerned with here is the routers folder.

This folder is what contains the all of the endpoints accessible in my API.

Notice that the folder contains three files in it.

Each file is a collection of endpoints related to a specific resource.

Here’s what the the pokemons.

js, which contains all the endpoints that make external calls to the PokeAPI, file looks like:Example 3Remember that async function we had before?.It actually lives in a file inside our controllers folder.

If we take a look at line 2 in Example 3, we’re telling our program to go into the controllers folder and grab the file that has the functions we need to use as callbacks in our router requests.

In this case the file is called pokemonControllers.

js .

I chose to set it up this way so that I can isolate all routes that require resources from external sources into one place.

Similarly, each file in my routers folder only concerns itself with one resource like user accounts and pokemon teams.

ConclusionThroughout the entire refactor process I did not touch the underlying logic that the original app used.

Instead I was able to condense the syntax and add more functionality overall.

The biggest impact to this refactor is that it makes it easier for me to add or modify features in the future.

What started off as a simple Node.

js api that simply made external api calls is now more robust and feature-full.

If you’re curious as to what the project looks like, here’s a link to the project Github repo.

.

. More details

Leave a Reply