Last active 1749834487

users,js Raw
1const mongoose = require("mongoose");
2const express = require("express");
3const Course = require("../mongoose/models/courses");
4
5const usersRouter = new express.Router();
6
7// Get all courses
8usersRouter.get("/courses/get", async (req, res) => {
9 try {
10 const courses = await Course.find({});
11 res.status(200).send(courses);
12 } catch (error) {
13 res.status(400).send({ error: "Failed to fetch courses" });
14 }
15});
16
17// Enroll in a course
18usersRouter.post("/courses/enroll/:id", async (req, res) => {
19 try {
20 const course = await Course.findById(req.params.id);
21 if (!course) {
22 return res.status(404).send({ error: "Course not found" });
23 }
24 if (course.isApplied) {
25 return res.status(403).send({ error: "Already enrolled in this course" });
26 }
27 course.isApplied = true;
28 await course.save();
29 res.status(200).send({ message: "Enrolled successfully" });
30 } catch (error) {
31 res.status(400).send({ error: "Failed to enroll in the course" });
32 }
33});
34
35// Drop a course
36usersRouter.delete("/courses/drop/:id", async (req, res) => {
37 try {
38 const course = await Course.findById(req.params.id);
39 if (!course) {
40 return res.status(404).send({ error: "Course not found" });
41 }
42 if (!course.isApplied) {
43 return res.status(403).send({ error: "Cannot drop an unenrolled course" });
44 }
45 course.isApplied = false;
46 await course.save();
47 res.status(200).send({ message: "Dropped the course successfully" });
48 } catch (error) {
49 res.status(400).send({ error: "Failed to drop the course" });
50 }
51});
52
53// Rate a course
54usersRouter.patch("/courses/rating/:id", async (req, res) => {
55 try {
56 const { rating } = req.body;
57 if (!rating || rating < 1 || rating > 5) {
58 return res.status(400).send({ error: "Invalid rating" });
59 }
60
61 const course = await Course.findById(req.params.id);
62 if (!course) {
63 return res.status(404).send({ error: "Course not found" });
64 }
65 if (!course.isApplied) {
66 return res.status(403).send({ error: "Cannot rate an unenrolled course" });
67 }
68
69 if (course.isRated) {
70 return res.status(403).send({ error: "Course has already been rated" });
71 }
72
73 // Update course rating
74 const totalRating = course.rating * course.noOfRatings;
75 const newTotalRating = totalRating + rating;
76 course.noOfRatings += 1;
77 course.rating = (newTotalRating / course.noOfRatings).toFixed(1);
78 course.isRated = true;
79 await course.save();
80
81 res.status(200).send({ message: "Rating added successfully" });
82 } catch (error) {
83 res.status(400).send({ error: "Failed to rate the course" });
84 }
85});
86
87module.exports = usersRouter;
88