Be the first user to complete this post
|
Add to List |
Organizing your expressjs routes in separate files.
The structure.
This is probably one of the simplest ways in which you can organize your express routes while still maintaining a good level of clarity.
The app.js acts as the starting point of the application. In this file, you instantiate
1. An instance of express - app
2. An instance of a configuration object - appEnv. This may contain information such as your database connection, any other common objects that needs to be shared by multiple route handlers.
One of the key advantages of this organization is that it makes it super easy to unit test express routes since you can stub your configuration objects for your test cases pretty easily.
We keep all of our routes handlers in the routes folder, organized by the routes they handle. But there are also 2 other files -
1. index.js:- This is the default file which gets loaded when you require the routes folder, or any other folder whatsoever. In this file, we export a function which receives an app and appEnv objects as arguments. These arguments are then passed down to the individual route handler functions in the same manner which themselves export a function the same way that index does.
2. main.js: - Any arbitrary routes that can't be grouped together logically in their own files (like users, orders, etc).
There are other approaches that let you require all the files in the routes folder directly in one command from the app.js itself instead of writing multiple require statements in the routes/index.js. If that works for you, its great, but I explicitly chose to stick to the approach described above for one main reason - When developing, if there's something wrong with a route, you can simply turn it off by commenting out a single line in routes/index.js. Whereas if you require all the files in a folder, you lose this flexibility. The downside of this approach is that whenever you plan to expose a new route, you have to remember to add it to your routes/index.js because adding it to the routes folder alone is not enough. I think I can live with that :).
The nodejs-starter-kit application uses the same structure as discussed above. If you are starting out afresh, you might want to try it out.
Also Read:
- How to publish a package on npm
- Unit test your Nodejs RESTful API using mocha
- Access the request body of a post request in your nodejs - expressjs app.
- What is npm shrinkwrap and when is it needed
- set the default node version using nvm