MERN Stack Learning App

Back - End - users.js

const express = require("express");
const Course = require("../mongoose/models/courses");

//setting up the student router
const usersRouter = express.Router();

//write your code here

//Post Method
usersRouter.post('/courses/enroll/:id', async (req, res, next) => {
    const id = req.params.id;
    const course = await Course.findById(id);
    try {
        if (course.isApplied) {
            return res.status(403).send({
                "message": "You have already applied for this course"
            })
        }
        course.isApplied = true;
        await course.save();
        return res.status(200).send({
            "message": "You have successfully enrolled for the course"
        });
    } catch (err) {
        res.sendStatus(400)
    }
})

//Delete Method
usersRouter.delete('/courses/drop/:id', async (req, res, next) => {
    const id = req.params.id;
    const course = await Course.findById(id);
    try {
        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 (err) {
        res.sendStatus(400)
    }
})


//Get Method
usersRouter.get('/courses/get', async (req, res, next) => {
    const courses = await Course.find();
    try {
        res.status(200).send(courses);
    } catch (error) {
        res.status(400).send({ error: error.message });
    }

})


//Patch Method
usersRouter.patch('/courses/rating/:id', async (req, res, next) => {
    const id = req.params.id;
    try {
        const course = await Course.findById(id);
        const { isApplied, isRated, noOfRatings, rating } = course
        if (!isApplied) {
            return res.status(403).send({
                "error": "You have not enrolled for this course"
            })
        }
        if (isRated) {
            return res.status(403).send({
                "error": "You have already rated this course"
            })
        }
        const newRating = req.body.rating;
        if (!newRating) {
            return res.sendStatus(400);
        }
        const resNoOfRatings = noOfRatings + 1;
        const resRating = (((rating || 0) * noOfRatings + newRating) / resNoOfRatings).toFixed(1);
        course.rating = resRating;
        course.noOfRatings = resNoOfRatings;
        course.isRated = true;
        await course.save();
        res.status(200).send({
            "message": "You have rated this course"
        })
    }
    catch {
        res.sendStatus(400);
    }

})
module.exports = usersRouter;

Front - End - App.js


import React, { Component } from "react";
import "./App.css";

class Home extends Component {
  BASE_URL = "http://localhost:8001/courses";
  state = {
    show: false,
    data: [],
    rating: 1,
  };
  componentDidMount = () => {
    // Write your code here
    this.handleGetData();
  };

  handleGetData = async () => {
    // Write your code here
    const res = await fetch(this.BASE_URL + "/get");
    this.setState({ data: await res.json() });
  };

  handleApply = async (id) => {
    // Write your code here
    const res = await fetch(this.BASE_URL + "/enroll/" + id, {
      method: "post",
      headers: { "Content-Type": "application/json" },
    });
    const data = await res.json();
    alert(data.message);
    this.handleGetData();
  };

  handleRating = (e) => {
    // Write your code here
    this.setState({ rating: e.target.value });
  };

  handleAddRating = async (id) => {
    // Write your code here
    const res = await fetch(this.BASE_URL + "/rating/" + id, {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ rating: this.state.rating }),
    });
    const { error } = await res.json();
    error && alert(error);
    this.handleGetData();
  };

  handleDrop = async (id) => {
    // Write your code here
    const res = await fetch(this.BASE_URL + "/drop/" + id, {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
    });
    const data = await res.json();
    alert(data.message);
    this.handleGetData();
  };

  render() {
    return (
      <div className="home">
        <header>
          <h2>ABC Learning</h2>
        </header>
        {/* write your code here */}
        <div className="cardContainer">
          {this.state.data.map((course) => {
            const {
              _id,
              courseName,
              courseDept,
              description,
              isApplied,
              isRated,
              duration,
              noOfRatings,
              rating,
            } = course;
            return (
              <div className="card" key={_id}>
                <ul>
                  <div className="header">
                    <li>{courseName}</li>
                    <li>{courseDept}</li>
                    <li>{description}</li>
                    {isApplied ? (
                      <li>
                        {!isRated && (
                          <li>
                            Rate:
                            <select
                              className="rating"
                              name="rating"
                              onChange={this.handleRating}
                            >
                              <option>1</option>
                              <option>2</option>
                              <option>3</option>
                              <option>4</option>
                              <option>5</option>
                            </select>
                            <button
                              className="rate"
                              onClick={() => {
                                this.handleAddRating(_id);
                              }}
                            >
                              Add
                            </button>
                          </li>
                        )}
                        <button
                          className="drop"
                          onClick={() => {
                            this.handleDrop(_id);
                          }}
                        >
                          Drop Course
                        </button>
                      </li>
                    ) : (
                      <li>
                        <button
                          className="btn"
                          onClick={() => {
                            this.handleApply(_id);
                          }}
                        >
                          Apply
                        </button>
                      </li>
                    )}
                  </div>
                  <div className="footer">
                    <li>
                      {duration} hrs . {noOfRatings} Ratings . {rating}/5
                    </li>
                  </div>
                </ul>
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}

export default Home;

Comments