OpenLake/Student_Database_COSA

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

Open

#226 创建于 2026年2月10日

在 GitHub 查看
 (2 评论) (0 反应) (0 负责人)JavaScript (56 fork)auto 404
Foss OverFlowbackendgood first issuerefactor

仓库指标

Star
 (13 star)
PR 合并指标
 (PR 指标待抓取)

描述

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).

贡献者指南