Skip to content

Commit

Permalink
Implemented getPost route
Browse files Browse the repository at this point in the history
  • Loading branch information
rosemdev committed Feb 20, 2024
1 parent 2eca9cb commit 403c0cf
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 17 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules
/images
/images
.vscode
49 changes: 33 additions & 16 deletions controllers/feed.js
Original file line number Diff line number Diff line change
Expand Up @@ -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!');
Expand All @@ -39,7 +35,7 @@ exports.createPost = (req, res, next) => {
},
});

return post
return post
.save()
.then((post) => {
res.status(201).json({
Expand All @@ -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);
});
};
3 changes: 3 additions & 0 deletions routes/feed.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,7 @@ router.post(
feedController.createPost
);

// GET /feed/posts
router.get('/posts/:postId', feedController.getPost);

module.exports = router;

0 comments on commit 403c0cf

Please sign in to comment.