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
94 changes: 94 additions & 0 deletions api/posts/posts-router.js
Original file line number Diff line number Diff line change
@@ -1 +1,95 @@
// implement your posts router here
const Post = require("./posts-model")
const express = require("express")
const router = express.Router()

router.get('/', (req, res) => {
Post.find(req)
.then(posts => {
res.status(200).json(posts)
})
.catch(err => {
res.status(500).json({message: 'The posts information could not be retrieved'})
})
})

router.get("/:id", (req, res) => {
const id = req.params.id
Post.findById(id)
.then(post => {
if(!post){
res.status(404).json('The post with the specified id does not exist')
} else {
res.json(post)
}
})
.catch(error => {
res.status(500).json({ message: error.message })
})
})

router.post('/', (req, res) => {
const newPost = req.body
Post.insert(newPost)
.then(post => {
res.status(201).json(newPost)
})
.catch(error => {
console.log(error);
res.status(500).json({
message: 'Error adding the post',
})
})
})

router.put('/:id', (req, res) => {
const changes = req.body
Post.update(req.params.id, changes)
.then(post => {
if(post) {
res.status(200).json(changes);
} else {
res.status(404).json({ message: 'The post could not be found' })
}
})
.catch(error => {
console.log(error);
res.status(500).json({
message: 'Error updating the adopter',
})
})
})

router.delete('/:id', (req, res) => {
Post.remove(req.params.id)
.then(count => {
if (count > 0) {
res.status(200).json({ message: 'The post has been nuked' })
} else {
res.status(404).json({ message: 'The posted could not be found' })
}
})
.catch(error => {
console.log(error);
res.status(500).json({
message: 'Error removing the post',
})
})
})

router.get("/:id/comments", (req, res) => {
const id = req.params.id
Post.findCommentById(id)
.then(comment => {
if(!comment){
res.status(404).json('The post with the specified id does not have comments')
} else {
res.json(comment)
}
})
.catch(error => {
res.status(500).json({ message: error.message })
})
})

module.exports = router
8 changes: 8 additions & 0 deletions api/server.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,10 @@
// implement your server here
// require your posts router and connect it here
const express = require("express")
const postRouter = require("./posts/posts-router")
const server = express()

server.use(express.json())
server.use("/api/posts", postRouter)

module.exports = server
4 changes: 4 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
// require your server and launch it here
const server = require('./api/server')
server.listen(1234, () => {
console.log('server is running on port 1234')
})
Loading