I'm currently working on a large web application with numerous routes. Currently, our routes are in one large list in a single JSON file. We recently ran into a problem due to the precedence of params being set from top to bottom in the file. This question details the issue we encountered further: Node.js Express route naming and ordering: how is precedence determined?
My plan is to propose an alternate routing solution based on my work from a personal project. I feel like it's a valid suggestion but missed out on a chance to really make my case in a meeting the other day. Here is a routes.js
file from my personal project that demonstrates the pattern I would like to use, let me know what you think or of possible better alternatives/edits. Thanks!
By creating separate routers for each resource, different controllers can access the same URLs without the params being overridden.
const express = require('express');
const usersRouter = express.Router();
const songsRouter = express.Router();
const playlistsRouter = express.Router();
const usersController = require('../controllers/users');
const songsController = require('../controllers/songs');
const playlistController = require('../controllers/playlists');
usersRouter.route('/')
.post(usersController.create)
songsRouter.route('/')
.get(songsController.index)
.post(songsController.create)
playlistsRouter.route('/')
.get(playlistController.index)
.post(playlistController.create)
songsRouter.route('/:id')
.get(songsController.show)
.put(songsController.update)
.delete(songsController.destroy)
playlistsRouter.route('/:id')
.get(playlistController.show)
.put(playlistController.update)
.delete(playlistController.destroy)
module.exports = {
songs: songsRouter,
playlists: playlistsRouter,
users: usersRouter,
};
A couple questions that come to my mind are:
- How optimal it would be to have all those Express router instances?
- Is this approach scalable?
1 Answer 1
absolutely, you should compose your express application in terms of a hierarchy of routers
instancing all those routers should be negligible in terms of your application's performance
this is the only approach i can imagine feasibly maintaining at scale, it buys you some separation of concerns
Explore related questions
See similar questions with these tags.