Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions api/models/books.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const mongoose = require('mongoose')
const Schema = mongoose.Schema

const schema = new Schema({
// _id: Schema.Types.ObjectId,
title: {
type: String,
required: true
},
published: {
type: Number,
required: true
},
authors: [{
name: {
type: String,
required: true
},
dob: {
type: String,
required: true
}
}]
}, {
timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }
})

module.exports = mongoose.model('Books', schema);
50 changes: 50 additions & 0 deletions api/routes/authors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
const router = require('express').Router({ mergeParams: true });
const Books = require('../models/books.js')

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great work on these routes!

// GET /api/books/:bookId/authors
router.get('/', async (req, res, next) => {
const status = 200
const authors = await Books.findById(req.params.bookId).select('authors')
res.json({ status, authors })
})

// GET /api/books/:bookId/authors/:authorId
router.get('/:authorId', async (req, res, next) => {
const status = 200
const book = await Books.findById(req.params.bookId)
const authorId = await book.authors.id(req.params.authorId)
res.json({ status, authorId })
})

// POST /api/books/:bookId/authors
router.post('/', async (req, res, next) => {
const status = 201
const book = await Books.findById(req.params.bookId)
book.authors.push(req.body)
await book.save()
const authors = await Books.findById(req.params.bookId).select('authors')
res.json({ status, authors })
})


// PUT /api/books/:bookId/authors/:authorId
router.put('/:authorId', async (req, res, next) => {
const status = 200
const book = await Books.findById(req.params.bookId)
const authorId = await book.authors.id(req.params.authorId)
Object.assign(authorId, req.body)
await book.save()
const authors = await Books.findById(req.params.bookId).select('authors')
res.json({ status, authors })
})

// DELETE /api/books/:bookId/authors/:authorId
router.delete('/:authorId', async (req, res, next) => {
const status = 200
const book = await Books.findById(req.params.bookId)
const authorRemoved = await book.authors.id(req.params.authorId).remove()
await book.save()
res.json({ status, authorRemoved })
})

module.exports = router
111 changes: 39 additions & 72 deletions api/routes/books.js
Original file line number Diff line number Diff line change
@@ -1,73 +1,40 @@
const router = require('express').Router()
const { generate: generateId } = require('shortid')

const books = [
{
id: 'j9U3iNIQi',
title: 'The Colour of Magic',
published: 1983,
authors: [
{
name: 'Sir Terry Pratchett',
dob: '04-28-1948'
}
]
},
{
id: 'ubQnXOfJV',
title: 'Stardust',
published: 1997,
authors: [
{
name: 'Neil Gaiman',
dob: '11-10-1960'
}
]
}
];

router.get('/', (req, res, next) => {
const status = 200
const response = books

res.json({ status, response })
})

router.post('/', (req, res, next) => {
const status = 201

books.push({ id: generateId(), ...req.body })
const response = books

res.json({ status, response })
})

router.get('/:id', (req, res, next) => {
const status = 200
const response = books.find(({ id }) => id === req.params.id)

res.json({ status, response })
})

router.put('/:id', (req, res, next) => {
const status = 200
const response = { id: req.params.id, ...req.body }
const single = books.find(({ id }) => id === req.params.id)
const index = books.indexOf(single)

books.splice(index, 1, response)

res.json({ status, response })
})

router.delete('/:id', (req, res, next) => {
const status = 200
const response = books.find(({ id }) => id === req.params.id)
const index = books.indexOf(response)

books.splice(index, 1)

res.json({ status, response })
})

const router = require('express').Router()
const Books = require('../models/books.js')

router.get('/', async (req, res, next) => {
const status = 200
const response = await Books.find().select('_id title published authors')
res.json({ status, response })
})

router.post('/', async (req, res, next) => {
const status = 201
const response = await Books.create(req.body)
res.json({ status, response })
})

router.get('/:id', async (req, res, next) => {
const status = 200
const response = await Books.findById(req.params.id).select('_id title published authors')
res.json({ status, response })
})

router.put('/:id', async (req, res, next) => {
const status = 200
const response = await Books.findOneAndUpdate({
_id: req.params.id
}, {
...req.body
}, {
new: true
}).select('_id title published authors')
res.json({ status, response })
})

router.delete('/:id', async (req, res, next) => {
const status = 200
const response = await Books.findOneAndDelete({_id: req.params.id}).select('_id title published authors')
res.json({ status, response })
})

module.exports = router
75 changes: 38 additions & 37 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,38 @@
const { MONGO_DB_CONNECTION, NODE_ENV, PORT } = process.env
const express = require('express')
const mongoose = require('mongoose')
const app = express()

// Database Connection
if (MONGO_DB_CONNECTION) {
mongoose.connect(MONGO_DB_CONNECTION, { useNewUrlParser: true })
console.log('Connected to database...')
} else {
console.log('Could not connect to database!')
}

// Application-level Middleware
if (NODE_ENV === 'development') app.use(require('morgan')('dev'))
app.use(require('body-parser').json())

// Routes
app.use('/api/books', require('./api/routes/books'))

// Not Found Handler
app.use((req, res, next) => {
const error = new Error(`Could not ${req.method} ${req.path}`)
error.status = 404
next(error)
})

// Error Handler
app.use((err, req, res, next) => {
if (NODE_ENV === 'development') console.error(err)
const { message, status } = err
res.status(status).json({ status, message })
})

// Open Connection
const listener = () => console.log(`Listening on Port ${PORT}!`)
app.listen(PORT, listener)
const { MONGO_DB_CONNECTION, NODE_ENV, PORT } = process.env
const express = require('express')
const mongoose = require('mongoose')
const app = express()

// Database Connection
if (MONGO_DB_CONNECTION) {
mongoose.connect(MONGO_DB_CONNECTION, { useNewUrlParser: true, useFindAndModify: false })
console.log('Connected to database...')
} else {
console.log('Could not connect to database!')
}

// Application-level Middleware
if (NODE_ENV === 'development') app.use(require('morgan')('dev'))
app.use(require('body-parser').json())

// Routes
app.use('/api/books', require('./api/routes/books'))
app.use('/api/books/:bookId/authors', require('./api/routes/authors'))

// Not Found Handler
app.use((req, res, next) => {
const error = new Error(`Could not ${req.method} ${req.path}`)
error.status = 404
next(error)
})

// Error Handler
app.use((err, req, res, next) => {
if (NODE_ENV === 'development') console.error(err)
const { message, status } = err
res.status(status).json({ status, message })
})

// Open Connection
const listener = () => console.log(`Listening on Port ${PORT}!`)
app.listen(PORT, listener)