Skip to content

Commit abb7079

Browse files
authored
Merge pull request #108 from rak-shit/post
Adds all the post API's
2 parents 73306e1 + 4b0e34d commit abb7079

File tree

5 files changed

+495
-48
lines changed

5 files changed

+495
-48
lines changed

app/controllers/post.js

Lines changed: 145 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,154 @@
1-
const userModel = require('../models/User')
2-
const bcrypt = require('bcrypt')
3-
const jwt = require('jsonwebtoken')
1+
const PostModel = require('../models/Post')
2+
const HANDLER = require('../utils/response-helper')
3+
const STATUS = require('../utils/status-codes')
4+
const imgUploadHelper = require('../utils/uploader')
5+
const consoleHelper = require('../utils/console-helper')
46

57
module.exports = {
6-
create: function (req, res, next) {
7-
userModel.create({ name: req.body.name, email: req.body.email, password: req.body.password }, function (err, result) {
8-
if (err) {
9-
next(err)
10-
} else {
11-
res.json({ status: 'success', message: 'User added successfully!!!', data: null })
8+
create: async (req, res, next) => {
9+
const post = new PostModel(req.body)
10+
const userId = req.user.id.toString()
11+
post.userId = userId
12+
if (req.file) {
13+
imgUploadHelper.mapToDb(req, post)
14+
}
15+
try {
16+
await post.save()
17+
res.status(STATUS.CREATED).json({ post })
18+
} catch (error) {
19+
HANDLER.handleError(res, error)
20+
}
21+
},
22+
delete: async (req, res, next) => {
23+
const { id } = req.params
24+
const userId = req.user.id.toString()
25+
try {
26+
const post = await PostModel.findById(id)
27+
if (!post) {
28+
return res.status(STATUS.NOT_FOUND).json({ message: 'No post exists' })
29+
}
30+
if (JSON.stringify(userId) !== JSON.stringify(post.userId)) {
31+
return res.status(STATUS.FORBIDDEN).json({ message: 'Bad delete request' })
1232
}
33+
await PostModel.findByIdAndRemove(id)
34+
res.status(STATUS.OK).json({ post: post, message: 'Deleted the post' })
35+
} catch (error) {
36+
HANDLER.handleError(res, error)
37+
}
38+
},
39+
updatePost: async (req, res, next) => {
40+
const { id } = req.params
41+
consoleHelper(id)
42+
const updates = Object.keys(req.body)
43+
const allowedUpdates = ['content', 'imgUrl']
44+
const userId = req.user.id.toString()
45+
const isValidOperation = updates.every((update) => {
46+
return allowedUpdates.includes(update)
1347
})
48+
49+
if (!isValidOperation) {
50+
return res.status(STATUS.BAD_REQUEST).json({ message: 'Invalid Update' })
51+
}
52+
try {
53+
const post = await PostModel.findById(id)
54+
if (!post) {
55+
return res.status(STATUS.BAD_REQUEST).json({ message: 'No post exists' })
56+
}
57+
if (JSON.stringify(userId) !== JSON.stringify(post.userId)) {
58+
return res.status(STATUS.FORBIDDEN).json({ message: 'Bad update request' })
59+
}
60+
consoleHelper(post)
61+
updates.forEach(update => {
62+
post[update] = req.body[update]
63+
})
64+
if (req.file) {
65+
imgUploadHelper.mapToDb(req, post)
66+
}
67+
await post.save()
68+
res.status(STATUS.UPDATED).json({ post: post })
69+
} catch (error) {
70+
HANDLER.handleError(res, error)
71+
}
1472
},
15-
authenticate: function (req, res, next) {
16-
userModel.findOne({ email: req.body.email }, function (err, userInfo) {
17-
if (err) {
18-
next(err)
19-
} else {
20-
if (bcrypt.compareSync(req.body.password, userInfo.password)) {
21-
const token = jwt.sign({ id: userInfo._id }, req.app.get('secretKey'), { expiresIn: '1h' })
22-
res.json({ status: 'success', message: 'user found!!!', data: { user: userInfo, token: token } })
23-
} else {
24-
res.json({ status: 'error', message: 'Invalid email/password!!!', data: null })
25-
}
73+
getPostById: async (req, res, next) => {
74+
const { id } = req.params
75+
try {
76+
const post = await PostModel.findById(id)
77+
if (!post) {
78+
return res.status(STATUS.NOT_FOUND).json({ error: 'Post not found' })
2679
}
27-
})
80+
res.status(STATUS.OK).json({ post: post })
81+
} catch (error) {
82+
HANDLER.handleError(res, error)
83+
}
2884
},
29-
test: function (req, res, next) {
30-
res.json({ success: 'ulllu' })
85+
getAllPost: async (req, res, next) => {
86+
try {
87+
const posts = await PostModel.find({})
88+
if (!posts.length) {
89+
return res.status(STATUS.NOT_FOUND).json({ message: 'No posts found' })
90+
}
91+
res.status(STATUS.OK).json({ posts: posts })
92+
} catch (error) {
93+
HANDLER.handleError(res, error)
94+
}
95+
},
96+
upvote: async (req, res, next) => {
97+
const { id } = req.params
98+
const userId = req.user.id.toString()
99+
try {
100+
const post = await PostModel.findById(id)
101+
if (!post) {
102+
return res.status(STATUS.NOT_FOUND).json({ error: 'No post found' })
103+
}
104+
// CHECKS IF THE USER HAS ALREADY UPVOTED THE COMMENT
105+
post.votes.upVotes.users.filter(user => {
106+
if (JSON.stringify(user) === JSON.stringify(userId)) {
107+
return res.status(STATUS.BAD_REQUEST).json({ error: 'Bad request' })
108+
}
109+
})
110+
// CHECKS IF THE USER HAS ALREADY DOWNVOTED THE COMMENT
111+
post.votes.downVotes.users.filter(user => {
112+
if (JSON.stringify(user) === JSON.stringify(userId)) {
113+
post.votes.downVotes.count = post.votes.downVotes.count - 1
114+
post.votes.downVotes.users.remove(user)
115+
}
116+
})
117+
post.votes.upVotes.count = post.votes.upVotes.count + 1
118+
post.votes.upVotes.users.push(userId)
119+
await post.save()
120+
res.status(STATUS.OK).json({ post: post, message: 'Success' })
121+
} catch (error) {
122+
HANDLER.handleError(res, error)
123+
}
124+
},
125+
downvote: async (req, res, next) => {
126+
const { id } = req.params
127+
const userId = req.user.id.toString()
128+
try {
129+
const post = await PostModel.findById(id)
130+
if (!post) {
131+
return res.status(STATUS.NOT_FOUND).json({ error: 'No post found' })
132+
}
133+
// CHECKS IF THE USER HAS ALREADY DOWNVOTED THE COMMENT
134+
post.votes.downVotes.users.filter(user => {
135+
if (JSON.stringify(user) === JSON.stringify(userId)) {
136+
return res.status(STATUS.BAD_REQUEST).json({ error: 'Bad request' })
137+
}
138+
})
139+
// CHECKS IF THE USER HAS ALREADY UPVOTED THE COMMENT
140+
post.votes.upVotes.users.filter(user => {
141+
if (JSON.stringify(user) === JSON.stringify(userId)) {
142+
post.votes.upVotes.count = post.votes.upVotes.count - 1
143+
post.votes.upVotes.users.remove(user)
144+
}
145+
})
146+
post.votes.downVotes.count = post.votes.downVotes.count + 1
147+
post.votes.downVotes.users.push(userId)
148+
await post.save()
149+
res.status(STATUS.OK).json({ post: post, message: 'Success' })
150+
} catch (error) {
151+
HANDLER.handleError(res, error)
152+
}
31153
}
32154
}

app/models/Post.js

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ const PostSchema = new Schema({
1313
}
1414
}
1515
},
16+
userId: {
17+
type: Schema.Types.ObjectId,
18+
ref: 'User'
19+
},
1620
image: {
1721
data: Buffer,
1822
contentType: String
@@ -32,26 +36,20 @@ const PostSchema = new Schema({
3236
type: Number,
3337
default: 0
3438
},
35-
users: {
36-
user: {
37-
type: Schema.Types.ObjectId,
38-
ref: 'User',
39-
required: true
40-
}
41-
}
39+
users: [{
40+
type: Schema.Types.ObjectId,
41+
ref: 'User'
42+
}]
4243
},
4344
downVotes: {
4445
count: {
4546
type: Number,
4647
default: 0
4748
},
48-
users: {
49-
user: {
50-
type: Schema.Types.ObjectId,
51-
ref: 'User',
52-
required: true
53-
}
54-
}
49+
users: [{
50+
type: Schema.Types.ObjectId,
51+
ref: 'User'
52+
}]
5553
}
5654
},
5755
comments: {

app/routes/post.js

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,57 @@
1+
require('../../config/mongoose')
12
const express = require('express')
23
const router = express.Router()
34
const userController = require('../controllers/post')
5+
const uploader = require('../utils/uploader')
6+
const auth = require('../middleware/auth')
47

58
// CREATE A POST
69
router.post(
710
'/',
11+
auth,
12+
uploader.upload.single('image'),
813
userController.create
914
)
1015

11-
// GET ALL POSTS OF A USER
16+
// GET ALL POSTS
1217
router.get(
13-
'/',
14-
userController.authenticate
15-
)
16-
17-
// GET PARTICULAR POST OF A USER
18-
router.get(
19-
'/:id',
20-
userController.test
18+
'/all_posts',
19+
auth,
20+
userController.getAllPost
2121
)
2222

2323
// UPDATE A TASK
2424
router.patch(
2525
'/:id',
26-
userController.test
26+
auth,
27+
uploader.upload.single('image'),
28+
userController.updatePost
2729
)
2830

2931
// DELETE A TASK
3032
router.delete(
3133
'/:id',
32-
userController.test
34+
auth,
35+
userController.delete
36+
)
37+
38+
// GET TASK BY ID
39+
router.get(
40+
'/:id',
41+
auth,
42+
userController.getPostById
43+
)
44+
45+
router.put(
46+
'/upvote/:id',
47+
auth,
48+
userController.upvote
49+
)
50+
51+
router.put(
52+
'/downvote/:id',
53+
auth,
54+
userController.downvote
3355
)
3456

3557
module.exports = router

app/utils/console-helper.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
const ConsoleHelper = (data) => {
2+
if (process.env.NODE_ENV === 'production') return
3+
console.log(data)
4+
}
5+
6+
module.exports = ConsoleHelper

0 commit comments

Comments
 (0)