Skip to content

Backend update, registration events#241

Open
vani-tcvostro wants to merge 1 commit intoOpenLake:mainfrom
vani-tcvostro:backend-update
Open

Backend update, registration events#241
vani-tcvostro wants to merge 1 commit intoOpenLake:mainfrom
vani-tcvostro:backend-update

Conversation

@vani-tcvostro
Copy link
Copy Markdown

@vani-tcvostro vani-tcvostro commented Mar 23, 2026


name: "Pull Request"
about: Propose and submit changes to the project for review
title: "PR: Add endpoint for student registered events"
labels: ""
assignees: harshitap1305, sakshi1755

Changes Introduced

  • Added: Backend endpoint to fetch all events a student has registered for (GET /api/students/:id/events).
  • Updated: Event model/controller logic to support querying registered participants.
  • Removed: N/A

Why This Change?

  • Problem: Currently, there is no way to programmatically fetch the events a student has registered for.
  • Solution: Added a backend endpoint that returns a list of registered events for a given student.
  • Impact: Enables the frontend (or other services) to display a student’s registered events, improving workflow and feature completeness.

Checklist

  • I have created a new branch for this PR (git checkout -b feature/student-events-endpoint).
  • My code follows the project's coding style and conventions.
  • My commit messages are clear and follow the project's guidelines.
  • I have performed a self-review of my own code.
  • All new and existing tests passed locally with my changes.
  • This PR introduces no breaking changes.

Deployment Notes

  • Requires a database migration/schema update: none
  • Requires new environment variables to be set: none
  • N/A

💬 Additional Notes

  • This endpoint is ready to be consumed by the frontend or other API clients.

Summary by CodeRabbit

  • New Features
    • Registered events retrieval: Users can now view all events they have registered for, providing centralized access to their event participation and making it easier to manage upcoming commitments.

@vercel
Copy link
Copy Markdown

vercel bot commented Mar 23, 2026

@vani-tcvostro is attempting to deploy a commit to the openlake's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 23, 2026

Walkthrough

Added a new endpoint to retrieve a user's registered events with authentication checks. Implemented controller logic in two separate files (dashboardController and eventControllers), integrated the endpoint via a new authenticated route in the events router, and refactored error handling in the event registration endpoint.

Changes

Cohort / File(s) Summary
Registered Events Controllers
backend/controllers/dashboardController.js, backend/controllers/eventControllers.js
Added two separate getRegisteredEvents controller implementations with authentication guards (401 on missing req.user), database queries to fetch events where participants contain the user ID, and standardized error handling returning 500 with "Server error" message.
Routes Integration
backend/routes/events.js
Added import for dashboardController, introduced new GET /registered-events route with isAuthenticated middleware delegating to dashboardController.getRegisteredEvents, refactored event registration error handling to distinguish CastError (400) from other errors (500), and adjusted formatting/closing braces.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • harshitap1305

Poem

🐰 Hop, hop, hooray! 🎉
Events now dance with registered users,
Auth shields guard the sacred gate,
Queries whisper through the database,
A new route hops into place—
The warren grows wiser!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Backend update, registration events' is vague and does not clearly convey the specific purpose of adding a student registered events endpoint. Consider using a more descriptive title such as 'Add endpoint to fetch student registered events' or 'Add GET /registered-events endpoint for fetching student events'.
✅ Passed checks (2 passed)
Check name Status Explanation
Description check ✅ Passed The PR description includes most required sections (Changes, Why, Checklist, Deployment Notes) but is missing Testing section with test case details and Screenshots section.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
backend/routes/events.js (1)

1-1: Consider importing from eventControllers instead.

Given that getRegisteredEvents handles event-related data, it would be more cohesive to keep it in eventControllers.js rather than dashboardController.js. The dashboard controller handles role-based stats, while this is a straightforward event query.

If you move the function to eventControllers.js (where a duplicate already exists), update this import accordingly and remove the duplicate from dashboardController.js.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/routes/events.js` at line 1, The route currently imports
getRegisteredEvents from dashboardController; move the getRegisteredEvents
function implementation to eventControllers.js (remove the duplicate in
dashboardController.js), then update the import in backend/routes/events.js to
require("../controllers/eventControllers") and reference the exported
getRegisteredEvents there; ensure the exported function name and any
dependencies (e.g., models or helper functions) are updated/required in
eventControllers.js and tests or other callers still reference
getRegisteredEvents.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@backend/controllers/eventControllers.js`:
- Around line 24-43: Remove the dead export exports.getRegisteredEvents from
backend/controllers/eventControllers.js since the route /registered-events is
wired to dashboardController.getRegisteredEvents; locate the function named
getRegisteredEvents (exports.getRegisteredEvents) in that file and delete the
entire async function block and its export to avoid duplication and confusion,
and run tests/lint to ensure no remaining references to
exports.getRegisteredEvents exist.

In `@backend/routes/events.js`:
- Around line 498-503: The "/registered-events" route registration using
router.get("/registered-events", isAuthenticated,
dashboardController.getRegisteredEvents) is declared after parameterized routes
(e.g., '/:id' and '/:eventId') so it will never be reached; relocate that
router.get(...) declaration to a position before any parameterized routes (for
example before the '/:eventId/is-contact' and '/:id' handlers) and remove the
duplicate declaration at the end of the file so the explicit
"/registered-events" path is matched first.
- Around line 259-264: The catch block in the events route has inconsistent
indentation for the lines handling CastError, console.error, and the
res.status(500) return; fix it by re-indenting the entire catch body so its
statements (the if (error?.name === "CastError") check, console.error("Event
registration error:", error), and return res.status(500).json(...)) align with
the surrounding function block style used in this file (ensure the same number
of spaces/tabs as other blocks in this handler to maintain consistent
formatting).

---

Nitpick comments:
In `@backend/routes/events.js`:
- Line 1: The route currently imports getRegisteredEvents from
dashboardController; move the getRegisteredEvents function implementation to
eventControllers.js (remove the duplicate in dashboardController.js), then
update the import in backend/routes/events.js to
require("../controllers/eventControllers") and reference the exported
getRegisteredEvents there; ensure the exported function name and any
dependencies (e.g., models or helper functions) are updated/required in
eventControllers.js and tests or other callers still reference
getRegisteredEvents.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d7d3c240-500e-4f7e-949e-b88e5a137ee4

📥 Commits

Reviewing files that changed from the base of the PR and between 060ea48 and b61571f.

⛔ Files ignored due to path filters (1)
  • backend/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • backend/controllers/dashboardController.js
  • backend/controllers/eventControllers.js
  • backend/routes/events.js

Comment on lines +24 to 43
exports.getRegisteredEvents = async (req, res) => {
try {

if (!req.user) {
return res.status(401).json({ message: "Unauthorized: Please login first" });
}

const userId = req.user._id;

const events = await Event.find({
participants: userId
});

res.status(200).json(events);

} catch (error) {
console.error("Error fetching registered events:", error);
res.status(500).json({ message: "Server error" });
}
}; No newline at end of file
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Dead code: this function is never used.

According to the route definition in backend/routes/events.js (lines 499-503), the /registered-events endpoint is wired to dashboardController.getRegisteredEvents, not this export. This implementation is identical to the one in dashboardController.js and is never called.

Remove this dead code to avoid confusion and maintenance burden.

🗑️ Proposed fix: remove unused function
-exports.getRegisteredEvents = async (req, res) => {
-    try {
-
-        if (!req.user) {
-            return res.status(401).json({ message: "Unauthorized: Please login first" });
-        }
-
-        const userId = req.user._id;
-
-        const events = await Event.find({
-            participants: userId
-        });
-
-        res.status(200).json(events);
-
-    } catch (error) {
-        console.error("Error fetching registered events:", error);
-        res.status(500).json({ message: "Server error" });
-    }
-};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
exports.getRegisteredEvents = async (req, res) => {
try {
if (!req.user) {
return res.status(401).json({ message: "Unauthorized: Please login first" });
}
const userId = req.user._id;
const events = await Event.find({
participants: userId
});
res.status(200).json(events);
} catch (error) {
console.error("Error fetching registered events:", error);
res.status(500).json({ message: "Server error" });
}
};
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/controllers/eventControllers.js` around lines 24 - 43, Remove the
dead export exports.getRegisteredEvents from
backend/controllers/eventControllers.js since the route /registered-events is
wired to dashboardController.getRegisteredEvents; locate the function named
getRegisteredEvents (exports.getRegisteredEvents) in that file and delete the
entire async function block and its export to avoid duplication and confusion,
and run tests/lint to ensure no remaining references to
exports.getRegisteredEvents exist.

Comment on lines +259 to +264
if (error?.name === "CastError") {
return res.status(400).json({ message: "Invalid event ID format." });
}
console.error("Event registration error:", error);
return res.status(500).json({ message: "Internal server error." });
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Inconsistent indentation in catch block.

The catch block content is not properly indented relative to the function body. This appears to be a formatting error.

🧹 Proposed fix: correct indentation
     } catch (error) {
-  if (error?.name === "CastError") {
-    return res.status(400).json({ message: "Invalid event ID format." });
-  }
-  console.error("Event registration error:", error);
-  return res.status(500).json({ message: "Internal server error." });
-}
+      if (error?.name === "CastError") {
+        return res.status(400).json({ message: "Invalid event ID format." });
+      }
+      console.error("Event registration error:", error);
+      return res.status(500).json({ message: "Internal server error." });
+    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/routes/events.js` around lines 259 - 264, The catch block in the
events route has inconsistent indentation for the lines handling CastError,
console.error, and the res.status(500) return; fix it by re-indenting the entire
catch body so its statements (the if (error?.name === "CastError") check,
console.error("Event registration error:", error), and return
res.status(500).json(...)) align with the surrounding function block style used
in this file (ensure the same number of spaces/tabs as other blocks in this
handler to maintain consistent formatting).

Comment on lines +498 to 503
// Get registered events
router.get(
"/registered-events",
isAuthenticated,
dashboardController.getRegisteredEvents
);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Critical: Route will never be reached due to ordering.

The /registered-events route is defined after the /:id route (line 269). Express matches routes in declaration order, so a request to /registered-events will be captured by /:id with id = "registered-events", resulting in a MongoDB CastError or unexpected behavior.

Move this route before all parameterized routes (/:id, /:eventId).

🐛 Proposed fix: move route before parameterized routes

Move the route definition to appear before line 151 (before /:eventId/is-contact), for example after line 12:

 router.get("/latest", eventsController.getLatestEvents);
 
+// Get registered events for authenticated user
+router.get(
+  "/registered-events",
+  isAuthenticated,
+  dashboardController.getRegisteredEvents
+);
+
 // Create a new event (new events can be created by admins only)
 router.post(
   "/create",

And remove lines 498-503 from the end of the file.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/routes/events.js` around lines 498 - 503, The "/registered-events"
route registration using router.get("/registered-events", isAuthenticated,
dashboardController.getRegisteredEvents) is declared after parameterized routes
(e.g., '/:id' and '/:eventId') so it will never be reached; relocate that
router.get(...) declaration to a position before any parameterized routes (for
example before the '/:eventId/is-contact' and '/:id' handlers) and remove the
duplicate declaration at the end of the file so the explicit
"/registered-events" path is matched first.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant