3
\$\begingroup\$

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:

  1. How optimal it would be to have all those Express router instances?
  2. Is this approach scalable?
\$\endgroup\$
2
\$\begingroup\$

absolutely, you should compose your express application in terms of a hierarchy of routers

  1. instancing all those routers should be negligible in terms of your application's performance

  2. this is the only approach i can imagine feasibly maintaining at scale, it buys you some separation of concerns

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.