Advertisement
Shell_Casing

Book store node.js app

May 3rd, 2018
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const Book = require('./mongoose-models');
  2.  
  3. module.exports = (app) => {
  4.  
  5.     // add a new book
  6.     app.post('/books', (req, res) => {
  7.         if(!req.body.title || !req.body.author || !req.body.genre) {
  8.             res.status(400).send({message: "Fill in all fields!"});
  9.         } else {
  10.             const book = new Book({
  11.                 title: req.body.title,
  12.                 author: req.body.author,
  13.                 genre: req.body.genre
  14.             });
  15.             book.save()
  16.                 .then(data => res.json(data))
  17.                 .catch(err => {
  18.                     res.status(500).send({message: err.message || "Oops: Something went wrong!"})
  19.                 });
  20.         }
  21.     });
  22.  
  23.  
  24.     // retrieve all books:
  25.     app.get('/books', (req, res) => {
  26.         Book.find()
  27.             .then(books => res.json(books))
  28.             .catch(err => {
  29.                 res.status(500).send({message: err.message || "Oops: Something went wrong!"})
  30.             });
  31.     });
  32.  
  33.  
  34.     // retrieve book by title:
  35.     app.get('/books/:title', (req, res) => {
  36.         Book.findOne({title: req.params.title}, (err, book) => {
  37.             if(err || !book) {
  38.                 res.status(500).send({message: err.message || "Oops: Something went wrong!"});
  39.             } else {
  40.                 res.send(book);
  41.             }
  42.         })
  43.     });
  44.  
  45.     // retrieve book by author:
  46.     app.get('/books/:author', (req, res) => {
  47.         Book.findOne({author: req.params.author}, (err, book) => {
  48.             if(err || !book) {
  49.                 res.status(500).send({message: err.message || "Oops: Something went wrong!"});
  50.             } else {
  51.                 res.send(book);
  52.             }
  53.         })
  54.     });
  55.  
  56.     // retrieve book by genre:
  57.     app.get('/books/:genre', (req, res) => {
  58.         Book.findOne({genre: req.params.genre}, (err, book) => {
  59.             if(err || !book) {
  60.                 res.status(500).send({message: "Oops: Something went wrong!"});
  61.             } else {
  62.                 res.send(book);
  63.             }
  64.         })
  65.     });
  66. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement