Jimmy’s Busy Cafe – A Perfect Parallel to Router in Express.js

Hello everyone! My name is Julian, and today we’re going to discuss routers.
But before diving into the details, let me share a recent experience which i had.

My cousin Jimmy always dreamed of owning a café in his hometown.
Every summer, he takes two months off to run his bustling café, where customers come in, place their orders, and wait to be served.
As the owner, he is responsible for ensuring that orders are taken, food is prepared, and customers are served in an organized and efficient manner.

The Chaos Without Organization:

  • When customers walk in, he take their orders, takes them to the kitchen, and then try to serve them.
    However, when there are too many customers, he gets overwhelmed.
    Orders get mixed up, and he has trouble remembering which order belongs to whom.
  • Sometimes, he forgets to check on other tasks, leading to delays and unhappy customers.

The Solution – Introducing a System of Servers:
So to solve this issue

  • He decided to hire several servers to handle different tasks:
    • Server 1: Takes the order.
    • Server 2: Sends the order to the kitchen.
    • Server 3: Serves the food to customers.

Now, instead of doing everything yourself, each server has a specific role.
Jimmy, as the manager, oversees the process, ensuring everything runs smoothly.
Each server can do their job without stepping on each other’s toes, and the overall system is much more organized.


Relating This to Express.js Router

In web development, the Express Router works similarly to the system of servers in the café:

  • Router in Express is like a group of servers that handle different types of tasks:
    • Routing: The router manages different routes (URLs) and organizes how requests are handled, so each route can be handled separately.

Just as having multiple servers in the café makes things more efficient and organized,
using Express Router helps organize and simplify the handling of routes in your application.


How the Router Makes It Better

Without a router, your Express app could become messy and difficult to manage, especially as the number of routes increases.
Let’s see how this works in practice.


Code Example Without Router:

const express = require(‘express’);

const app = express();

// Handling everything in one file

app.get(‘/orders’, (req, res) => {

    res.send(‘Order List’);

});

app.post(‘/orders’, (req, res) => {

    res.send(‘Order Created’);

});

app.get(‘/users’, (req, res) => {

    res.send(‘User List’);

});

app.post(‘/users’, (req, res) => {

    res.send(‘User Created’);

});

app.listen(3000, () => {

    console.log(‘Server is running on port 3000’);

});

Issues:

  • Everything is in one file, making it hard to scale as the project becomes complex.
  • As the app grows, you have to keep adding more routes, making the code messy and harder to maintain.

How the Router Makes It Better

By splitting routes into separate files and using Express Router, we can create a more organized and scalable structure for our application. Let’s implement this approach:


1. Main Application File (app.js)

This file serves as the entry point and integrates the routers for different sections of the app:

const express = require(‘express’);

const app = express();

// Import routes

const ordersRouter = require(‘./routes/orders’);

const usersRouter = require(‘./routes/users’);

// Use routers

app.use(‘/orders’, ordersRouter);

app.use(‘/users’, usersRouter);

// Start the server

app.listen(3000, () => {

    console.log(‘Server is running on port 3000’);

});


2. Orders Routes (routes/orders.js)

This file handles all routes related to orders.

const express = require(‘express’);

const router = express.Router();

// Get all orders

router.get(‘/’, (req, res) => {

    res.send(‘Order List’);

});

// Create a new order

router.post(‘/’, (req, res) => {

    res.send(‘Order Created’);

});

module.exports = router;

Additional: 

 Will also talk about other types of request that one can work with such as 

// Update an existing order

router.put(‘/:orderId’, (req, res) => {

    const { orderId } = req.params;

    res.send(`Order ${orderId} Updated`);

});

// Delete an order

router.delete(‘/:orderId’, (req, res) => {

    const { orderId } = req.params;

    res.send(`Order ${orderId} Deleted`);

});


3. Users Routes (routes/users.js)

This file handles all routes related to users.

const express = require(‘express’);

const router = express.Router();

// Get all users

router.get(‘/’, (req, res) => {

    res.send(‘User List’);

});

// Create a new user

router.post(‘/’, (req, res) => {

    res.send(‘User Created’);

});

module.exports = router;


Advantages of Using Separate Routes

  1. Organization: Routes are grouped logically (e.g., orders, users) in separate files, keeping the codebase clean and structured.
  2. Maintainability: Makes it easier to add, modify, or remove routes without touching the main application logic.
  3. Scalability: Allows effortless addition of new modules (e.g., products, payments) without cluttering the main application file.

How It Works

  1. Requests to /orders are handled by the ordersRouter in routes/orders.js.
  2. Requests to /users are handled by the usersRouter in routes/users.js.
  3. The app.js file acts as the central point to integrate and manage all these routers.

This modular structure ensures your app remains maintainable and scalable as it grows.

Conclusion:

  1. Divides Work: Express Router splits routes (like orders and users) into separate files, similar to assigning specific tasks to café staff.
  2. Keeps Things Organized: Avoids the mess of cramming everything into one file, just like dividing roles in a café keeps operations smooth.
  3. Easier to Expand: Adding new features in the app is simpler, like hiring more staff to handle increased café demand.
  4. Improves Efficiency: Each router handles its task independently, ensuring the app stays maintainable, just like staff focusing on their roles.
  5. Supports Growth: The structure allows the app to grow without chaos, just as a well-organized café handles more customers effortlessly.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *