Structuring Express Controllers In An Efficient Way

Ganga Siva Krishna Palla
2 min readFeb 24, 2019

For this post ,I’m going to talk about how to write a more modular,extensible,testable and scalable implementation of your routing.Whether you’re writing an API or the back-end for your front-end, you may find this useful.

I created an organization system for app’s controllers which i paired with a loader.

✓ Here is how to setup a controllers architecture.

Detailed Server Implementation

Entry Point:

/app.js

This is the entry point for our server.Here we are using our home loader Avis to load the controllers.

Avis Loader :

It will go through the controllers, read the route definition files, and load routes.

The Structure of controllers

I designed the organization method to have wide compatibility, which means that someday you’ll not be locked into a kind of use case you can’t solve with this method.

Setup your file tree:

Let’s see how it looks

controllers structure

Load your routes
█▒▒▒▒▒▒▒▒▒

To make things work following the structure defined above, we need to use a simple loader I created: Avis. It will go through the controllers, read the files, and load routes.

You can check to code source on GitHub.

Routing files

They have been designed to be easy to read. The purpose is to be able to identify methods to update in development by having a quick look in your .routing files. Avis uses the name of the folder in which the routing file is to prefix routes.

[POST] /student

[GET] /student

[GET]/student/:id

As you can see above, each routes configuration have an action method which is nothing more than the logic to execute when we call your API route. I recommend keeping in one file: one action method and its optional associated middleware.

I hope you find it useful for your current or future expressjs projects :)

Thanks for reading.

--

--