{"size": 3687, "ext": "js", "max_stars_repo_path": "src/controllers/borrow.js", "max_stars_repo_name": "pulidovpe/mean-library", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/controllers/borrow.js", "max_issues_repo_name": "pulidovpe/mean-library", "max_issues_repo_issues_event_min_datetime": "2021-01-08T13:24:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-08T13:24:58.000Z", "max_forks_repo_path": "src/controllers/borrow.js", "max_forks_repo_name": "pulidovpe/mean-library", "max_forks_repo_forks_event_min_datetime": "2018-10-22T22:41:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-22T22:41:37.000Z"}
{"max_stars_count": null, "max_issues_count": 7, "max_forks_count": 1, "avg_line_length": 33.5181818182, "max_line_length": 108, "alphanum_fraction": 0.5484133442}
const Borrow = require('../models/Borrow');
const Book = require('../models/Book');

async function getBorrows(req,res) {
   try {
      await Borrow.find({state: 'current'}).populate([
         {path: 'user_id', model: 'User'},
         {path: 'book_id', model: 'Book'}
      ]).exec((err, brws) => {
        if(err || brws === undefined) res.status(404).send({ error: 'Something failed. Not found!' });
        else {
          res.status(200).json(brws);
          /*console.log('Lets show data: ' + brws);*/
        }
      });
   } catch(err) {
      console.log(`err: ${err.status} - name: ${err.name} - message: ${err.message}`);
      return res.status(404).json({ error: err.message });
   }
}

async function getBorrow(req,res) {
   try {
      const _id = req.params.id;
      await Borrow.findOne({_id}).populate([
         {path: 'user_id', model: 'User'},
         {path: 'book_id', model: 'Book'}
      ]).exec((err, brws) => {
        if(err || brws === undefined) {
          res.sendStatus(err.status || 404);
          console.log(`err: ${err.status} - message: ${err.message}`);
        } else res.json(brws);
      });
   } catch(err) {
      console.log(`err: ${err.status} - name: ${err.name} - message: ${err.message}`);
      return res.status(404).json({ error: err.message });
   }
}
// borrow a book
async function saveBorrow(req,res) {
   try {
      const { user_id, book_id } = req.body;
      const newBorrow = new Borrow({ user_id, book_id });
      await newBorrow.save()
      .then(async () => {
         await Book.findByIdAndUpdate(book_id, {state: 'inactive'})
         .exec((err) => {
            if(err) res.status(404).send({ error: 'Something failed. Not found!' });
            else {
               console.log(JSON.stringify(newBorrow));
               res.status(200).send({ status: 'Borrow created' });
            }
         });
      });
   } catch(err) {
      console.log(`err: ${err.status} - name: ${err.name} - message: ${err.message}`);
      if (err.name === 'ValidationError') {
        return res.status(400).json({ error: err.message });
      }
      return res.status(404).json({ error: err.message });
   }
}
// return a book
async function updateBorrow(req,res) {
   try {
      const { id, book_id } = req.params;
      const today = new Date();
      const updBorrow = { date_due: today, state: 'expired' };
      await Borrow.findByIdAndUpdate(id, updBorrow)
      .then(async () => {
         await Book.findByIdAndUpdate(book_id, {state: 'active'})
         .exec((err, book) => {
            if(err || book === undefined) res.status(404).send({ error: 'Something failed. Not updated!' });
            else {
               console.log(JSON.stringify(updBorrow));
               res.status(200).send({ status: 'Borrow updated' });
            }
         });
      });
   } catch(err) {
      console.log(`err: ${err.status} - name: ${err.name} - message: ${err.message}`);
      if (err.name === 'ValidationError') {
        return res.status(400).json({ error: err.message });
      }
      return res.status(404).json({ error: err.message });
   }
}

async function deleteBorrow(req,res) {
   try {
      const id = req.params.id;
      await Borrow.findByIdAndRemove(id);
      res.status(200).send({ status: 'Borrow deleted' });
   } catch (err) {
      console.log(`err: ${err.status} - name: ${err.name} - message: ${err.message}`);
      if (err.name === 'ValidationError') {
        return res.status(400).json({ error: err.message });
      }
      return res.status(404).json({ error: err.message });
   }
}

module.exports = {
   getBorrow,
   getBorrows,
   saveBorrow,
   updateBorrow,
   deleteBorrow
}
