Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
books.js 1.92 KiB
var express = require('express');
var bookRouter = express.Router();
var Book = require('../../models/book')

/* GET books listing. */

bookRouter.use('/', (req, res, next)=>{
  console.log("I run first before any http request")
  next()
})

bookRouter.use('/:bookId', (req, res, next)=>{
  console.log("I run only when I match the /:bookId route")
  Book.findById( req.params.bookId, (err,book)=>{
    if(err)
        res.status(404).send(err)
    else {
        req.book = book;
        next()
    }
  })
})
bookRouter.route('/')
  .get((req, res) => {
    Book.find({}, (err, books) => {
      res.json(books)
    })
  })  
  .post((req, res) => {
    let book = new Book(req.body); 
    book.save();
    res.status(201).send(book) 
  });


bookRouter.route('/:bookId')
  .get((req, res) => {
    //querying the database for a book that matches the bookID parameter from the URL request
   // Book.findById(req.params.bookId, (err, book) => {
     // res.json(book)
      // when using middleware
      res.status(200).json(req.book)
    //}) 
  })
  .put((req,res) => {
    //first retrieve the instance of the resource you want
    //update its values
    //Book.findById(req.params.bookId, (err, book) => {
      //  book.title = req.body.title;
        //book.author = req.body.author;
        //book.save()
        //res.json(book)
        
        // when using middleware
        req.book.title = req.body.title;
        req.book.author = req.body.author;
        req.book.save()
        res.json(req.book)
    
  })
  .delete((req,res)=>{
    Book.findById(req.params.bookId, (err, book) => {
        // with middleware
        //  req.book.remove(err => {
        if(err)
          res.status(404).send(err)
        book.remove(err => {
            if(err){
                res.status(500).send(err)
            }
            else{
                res.status(204).send('removed')
            }
        })
    })
  })
  
    

module.exports = bookRouter;