diff --git a/.gitignore b/.gitignore index a34acd5..4b375d3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ node_modules -/images \ No newline at end of file +/images +.vscode \ No newline at end of file diff --git a/controllers/feed.js b/controllers/feed.js index 56b9308..69a810a 100644 --- a/controllers/feed.js +++ b/controllers/feed.js @@ -2,24 +2,20 @@ const { validationResult } = require('express-validator'); const Post = require('../models/post'); exports.getPosts = (req, res, next) => { - res.status(200).json({ - posts: [ - { - _id: '123', - title: 'First Post', - content: 'This is the first post!', - imageUrl: 'images/gift.jpg', - createdAt: new Date(), - creator: { - name: 'Roma', - }, - }, - ], - }); + Post.find() + .then((posts) => { + res.status(200).json({ message: 'Posts are fetched', posts: posts }); + }) + .catch((err) => { + if (!err.statusCode) { + err.statusCode = 500; + } + next(err); + }); }; exports.createPost = (req, res, next) => { - const errors = validationResult(req); + const errors = validationResult(req); if (!errors.isEmpty()) { const error = new Error('Validation Failed!'); @@ -39,7 +35,7 @@ exports.createPost = (req, res, next) => { }, }); - return post + return post .save() .then((post) => { res.status(201).json({ @@ -54,3 +50,24 @@ exports.createPost = (req, res, next) => { next(err); }); }; + +exports.getPost = (req, res, next) => { + const postId = req.params.postId; + + Post.findById(postId) + .then((post) => { + if (!post) { + const error = new Error('No post foound with the id: ' + postId); + error.statusCode = 404; + throw error; + } + + res.status(200).json({ message: 'Post is fetched', post: post }); + }) + .catch((err) => { + if (!err.statusCode) { + err.statusCode = 500; + } + next(err); + }); +}; diff --git a/routes/feed.js b/routes/feed.js index 0f690df..fe5060f 100644 --- a/routes/feed.js +++ b/routes/feed.js @@ -24,4 +24,7 @@ router.post( feedController.createPost ); +// GET /feed/posts +router.get('/posts/:postId', feedController.getPost); + module.exports = router;