Creating a comment's HTTP requests

Now create the HTTP request functions for the Comment

Here is the function for creating a comment's POST request:

// Post comment in a post by Profile ID and Post ID
@PostMapping("/comment/{post_id}")
fun postCommentByPostId(@PathVariable("post_id") postId: Long, @RequestParam id: Long, @RequestParam commentText: String): Any {
val optionalPost: Optional<Post> = postRepository.findById(postId)
return if (optionalPost.isPresent) {
val myComment = Comment(commentText, Profile(id))
val post = optionalPost.get()
post.comments.add(myComment)
postRepository.save(post)
return post
} else {
"There is no post.."
}
}

First, we need to initialize an optionalPost object by finding the existing post. Then, if the post exists, we create a Comment model named myComment, then add the mutable list of Comment, and then save the post using postRepository.

Here is the function for creating a comment's GET request:

// get comment List of a post
@GetMapping("/comment/{id}")
fun getCommentListByPostId(@PathVariable("id") id: Long): Any {
return commentRepository.findById(id)
}

Here is the function for creating a comment's PUT request:

// get comment List of a post
@GetMapping("/comment/{id}")
fun getCommentListByPostId(@PathVariable("id") id: Long, @RequestParam text: String): Any {
val modifiedComment = commentRepository.getOne(id)
modifiedComment.text = text
return commentRepository.save(modifiedComment)
}

Here is the function for creating a comment's DELETE request:

// delete comment List of a status
@DeleteMapping("/comment/{id}")
fun deleteCommentByPostId(@PathVariable("id") id: Long): Any {
return commentRepository.findById(id)
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.34.226