Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | 3x 3x 1x 1x 1x 1x 3x 2x 2x 2x 3x 3x 3x 3x | const Book = require('../books/book.model')
// Create new book
const postABook = async (req, res) => {
try {
const newBook = new Book(req.body)
await newBook.save()
res.status(201).json(newBook)
} catch (error) {
console.error('Error creating book', error)
res.status(500).json({ message: error.message })
}
}
// Get all books
const getAllBooks = async (req, res) => {
try {
const books = await Book.find()
res.json(books)
} catch (error) {
console.error('Error fetching books', error)
res.status(500).json({ message: error.message })
}
}
// Get single book
const getSingleBook = async (req, res) => {
try {
const book = await Book.findById(req.params.id)
if (!book) {
res.status(404).send({ message: 'Book not Found!' })
}
res.status(200).send(book)
} catch (error) {
console.error('Error fetching book', error)
res.status(500).json({ message: error.message })
}
}
// Update book data
const updateBook = async (req, res) => {
try {
const updatedBook = await Book.findByIdAndUpdate(req.params.id, req.body, {
new: true,
})
if (!updatedBook) {
res.status(404).send({ message: 'Book is not Found!' })
}
res.status(200).send(updatedBook)
} catch (error) {
console.error('Error updating a book', error)
res.status(500).send({ message: error.message })
}
}
// Delete a book
const deleteABook = async (req, res) => {
try {
const { id } = req.params
const deletedBook = await Book.findByIdAndDelete(id)
if (!deletedBook) {
res.status(404).send({ message: 'Book is not Found!' })
}
res.status(200).send(deletedBook)
} catch (error) {
console.error('Error deleting a book', error)
res.status(500).send({ message: error.message })
}
}
module.exports = {
postABook,
getAllBooks,
getSingleBook,
updateBook,
deleteABook,
}
|