{"size": 1725, "ext": "js", "max_stars_repo_path": "src/api/admin/reviews.js", "max_stars_repo_name": "Thefakedeal/travelbuddy-frontend", "max_stars_repo_stars_event_min_datetime": "2021-05-30T14:55:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T14:55:17.000Z", "max_issues_repo_path": "src/api/admin/reviews.js", "max_issues_repo_name": "Thefakedeal/travelbuddy-frontend", "max_issues_repo_issues_event_min_datetime": "2021-06-10T17:37:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-12T17:16:57.000Z", "max_forks_repo_path": "src/api/admin/reviews.js", "max_forks_repo_name": "Thefakedeal/travelbuddy-frontend", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": 2, "max_forks_count": null, "avg_line_length": 26.5384615385, "max_line_length": 89, "alphanum_fraction": 0.5971014493}
const router = require('express').Router();
const Review = require('../../model/Review');

const { param, validationResult } = require("express-validator");
const mongoose = require('mongoose')

const isValidObjectId = param("id").custom((value) => {
  const isValid = mongoose.Types.ObjectId.isValid(value);
  if (!isValid) throw new Error("Invalid ID");
  return isValid;
});


router.get('/', async(req,res,next)=>{
    try{
        const reviews = await Review.find({}).populate("user","-password");
        res.json({data: reviews});
    }catch(err){
        next(err)
    }
})

router.get('/flagged', async(req,res,next)=>{
    try{
        const reviews = await Review.find({flagged: true}).populate("user","-password");
        res.json({data: reviews});

    }catch(err){
        next(err)
    }
})


router.get('/:id', isValidObjectId, async(req,res,next)=>{
    try{
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
          return res.status(400).json({ errors: errors.array() });
        }

        const review = await Review.findById(req.params.id).populate("user","-password");
        if(!review) return res.sendStatus(404);
        res.json(review);
    }catch(err){
        next(err)
    }
})


router.delete('/:id', isValidObjectId, async(req,res,next)=>{
    try{
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
          return res.status(400).json({ errors: errors.array() });
        }

        const review= await Review.findByIdAndDelete(req.params.id);
        if(!review) return res.sendStatus(404);
        return res.status(203).json({message: "Review Deleted"});
    }catch(err){
        next(err)
    }
})

module.exports = router;