Skip to content

[FOSSOVERFLOW-25] Refactor: Backend- Migrate Logic from Routes to Controllers #226

Description

@harshitap1305

NOTE: THIS ISSUE IS FOR FOSSOVERFLOW MENTEE

Currently, most of the backend logic (database queries, validation, and response handling) is implemented directly within the route handlers ( in backend/routes/). This makes the routes bulky and harder to test or reuse.

This task is to refactor the backend to follow the Controller Pattern. We want to extract the logic into dedicated controller files, leaving the routes responsible only for defining endpoints and middleware chains.

There should be NO changes to the logic itself. This is a structural refactor only.

Objectives

  1. Cleaner Routes: Route files should only contain the path, the HTTP method, middleware (auth, uploads), and a reference to the controller function.
  2. Modular Controllers: Logic for each resource (User, Event, Position, etc.) should be encapsulated in a corresponding controller file.
  3. Improved Readability: Separating "how we find the data" from "where the endpoint is" makes the codebase easier for new contributors to understand.

Implementation Pattern

Current State (Bloated Route):

// routes/eventRoutes.js
router.post("/add-event", async (req, res) => {
  try {
    const newEvent = new Event(req.body);
    await newEvent.save();
    res.status(201).json(newEvent);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

Desired State (Refactored):

  1. Create the Controller:
// controllers/eventController.js
const { Event } = require("../models/schemas");

exports.createEvent = async (req, res) => {
  try {
    const newEvent = new Event(req.body);
    await newEvent.save();
    res.status(201).json(newEvent);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};
  1. Update the Route:
// routes/eventRoutes.js
const eventController = require("../controllers/eventController");

router.post("/add-event", eventController.createEvent);

Task Checklist

[ ] Identify all routes currently containing async (req, res) => { ... } blocks.

[ ] Create corresponding controller files in the controllers/ directory:

[ ] Move the logic from each route into a named exported function in the controller.

[ ] Update the route files to import the controllers and call the appropriate functions.

[ ] Verify: Ensure all API endpoints still function exactly as before (test via Postman or the frontend).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions