TCS Mern
usersRouter.get("/courses/get", async(req, res) => {
try {
const courses await Course.find({});
res.status (200).send(courses);
catch (error) {
res.status (400).send({ error: "Failed to fetch courses" });
});
usersRouter.post("/courses/enroll/:id", async(req, res) => {
try {
const course await Course.findById(req.params.id);
if(!course) {
return res.status(400).send({ error: "Course not found"));
}
if(course.isApplied) {
return res.status(403).send((error: You have already applied for this course" });
}
course.isApplied = true;
await course.save();
res.status(200).send({message: "You have successfully enrolled for the course" })
} catch (error) {
return res.status(400).send({ error: "Failed to enroll the course" });
}
});
usersRouter.delete("/courses/drop/:id", async(req, res) => {
try {
const course await Course.findById(req.params.id);
if(!course){
return res.status(400).send({ error: "Course not found" });
}
if(!course.isApplied) {
return res.status(403).send({ error: "You have not enrolled for this course" });
}
course.isApplied = false;
await course.save();
return res.status(200).send({message: "You have dropped the course" });
} catch (error) {
return res.status(400).send({ error: "Failed to drop the course" });
}
});
usersRouter.patch("/courses/rating/:id", async(req, res) => {
try {
const { rating} = req.body;
if(!rating || rating < 1 || rating > 5){
return res.status(400).send({ message: "Invalid rating" });
}
const course = await Course.findById(req.params.id);
if(!course) {
return res.status(400).send({ error: "Course not found" });
}
if(!course.isApplied) {
return res.status(403).send({ erroг: "You have not enrolled for this course" });
}
if(course.isRated) {
return res.status(403).send({ error: "Course has already been rated" });
}
const totalRating = course.rating course.noofRatings;
const newTotalRating = totalRating + rating;
course.noofRatings += 1;
course.rating = (newTotalRating / course.noofRatings).toFixed(1);
course.isRated = true;
await course.save();
res.status(200).send({ message: "You have rated this course" });
} catch (error) {
return res.status(400).send() error: "Failed to update the course");
}
})