diff --git a/comment-service/src/controllers/Comment.ts b/comment-service/src/controllers/Comment.ts index 153ddd00961c93822a2efbc87433beaa320b256d..e28e27341108b09facb122cdc85715284953a4e3 100644 --- a/comment-service/src/controllers/Comment.ts +++ b/comment-service/src/controllers/Comment.ts @@ -7,6 +7,9 @@ import { config } from "../config/config"; import Logging from "../library/logging"; const createComment = async ( req: Request, res: Response, next: NextFunction,) => { + + + const { post_id, user_id, body} = req.body; const comment = new Comment({ @@ -16,35 +19,66 @@ const createComment = async ( req: Request, res: Response, next: NextFunction,) body }); + + //Try Catach Block to test for whether Post Exsits + /* + try{ + + const posts = {post_id : new mongoose.Types.ObjectId(post_id)} + const post_exist = await Comment.countDocuments(posts, { limit: 1 }) + if(post_exist == 0) { + return res.status(404).send({message: 'The specified post or user does not exist.'}); + } + } + catch{ + return res.status(404).send({message: 'The specified post or user does not exist.'}); + + } + */ + + //Try Catch Block to test whether Users Exsits + /* + try{ + + const users = {post_id : new mongoose.Types.ObjectId(user_id)} + const users_exist = await Comment.countDocuments(users, { limit: 1 }) + if(users_exist == 0) { + return res.status(404).send({message: 'The specified post or user does not exist.'}); + } + } + catch{ + return res.status(404).send({message: 'The specified post or user does not exist.'}); + + } + */ + + - let token = req.headers.authorization?.split(' ')[1]; + const token = req.headers.authorization?.split(' ')[1]; if (!token) { - return res.status(401).send({ message: 'Unauthorized' }); + return res.status(400).send({ message: 'Bad Request' }); } - const decodedToken = jwt.verify(token, config.server.token.secret ); - const decodeTokenToString = decodedToken; - const tokenString = JSON.stringify(decodeTokenToString); - const JSobj = JSON.parse(tokenString).user_id; + try { + const decodedToken = jwt.verify(token, config.server.token.secret ); + const decodeTokenToString = decodedToken; + const tokenString = JSON.stringify(decodeTokenToString); + const JSobj = JSON.parse(tokenString).user_id; if(JSobj == user_id){ const comment_1 = await comment .save(); return res.status(201).json({ comment_1 }); } else{ - + return res.status(401).send({ message: 'Unauthorized' }); } - - - - } catch (error) { - return res.status(500).json({ error }); + return res.status(400).json({ message: 'Bad Request' }); } };