Skip to content
Snippets Groups Projects
Commit 3c8ed806 authored by Richard Githuba's avatar Richard Githuba
Browse files

finished the like functionality

parent 1e5c302c
No related branches found
No related tags found
No related merge requests found
......@@ -151,34 +151,42 @@ public class FeedApisController {
// liking a post
@PostMapping("/{postId}/like")
public ResponseEntity<Void> likePost(@PathVariable int postId, @RequestParam int userId) {
public ResponseEntity<Void> likePost(@PathVariable int postId) {
try {
feedRepository.likePost(postId, userId);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User currentUser = userService.findByEmail(auth.getName());
feedRepository.likePost(postId, currentUser.getId());
return ResponseEntity.ok().build();
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
// removing a like from post
// remove like from post
@DeleteMapping("/{postId}/like")
public ResponseEntity<Void> unlikePost(@PathVariable int postId, @RequestParam int userId) {
public ResponseEntity<Void> unlikePost(@PathVariable int postId) {
try {
feedRepository.unlikePost(postId, userId);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User currentUser = userService.findByEmail(auth.getName());
feedRepository.unlikePost(postId, currentUser.getId());
return ResponseEntity.ok().build();
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
// getting list of likes from a post
// check if already liked
@GetMapping("/{postId}/hasLiked")
public ResponseEntity<Boolean> hasUserLikedPost(@PathVariable int postId, @RequestParam int userId) {
public ResponseEntity<Boolean> hasUserLikedPost(@PathVariable int postId) {
try {
boolean hasLiked = feedRepository.hasUserLikedPost(postId, userId);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User currentUser = userService.findByEmail(auth.getName());
boolean hasLiked = feedRepository.hasUserLikedPost(postId, currentUser.getId());
return ResponseEntity.ok(hasLiked);
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
}
\ No newline at end of file
......@@ -254,4 +254,9 @@ form > label > input,textarea {
#closeModalBtn {
cursor: pointer;
}
\ No newline at end of file
}
.like-button.liked {
color: #007bff;
font-weight: bold;
}
......@@ -79,16 +79,18 @@ async function renderPost(post) {
}
// set the count of the likes
const likeButton = postElement.querySelector('.like-button');
const likeCount = postElement.querySelector('.like-count');
likeCount.textContent = post.likesCount || 0;
likeButton.addEventListener('click', () => handleLike(post.postId, likeCount, likeButton));
// timestamp
const timestamp = postElement.querySelector('.timestamp');
timestamp.textContent = new Date(post.postTime).toLocaleDateString();
// add a like when presses
const likeButton = postElement.querySelector('.like-button');
likeButton.addEventListener('click', () => handleLike(post.postId, likeCount));
// Set data attributes for reference
const postDiv = postElement.querySelector('.post');
......@@ -123,32 +125,33 @@ async function renderPost(post) {
}
// add a like if user had not already liked and remove a like if already liked
async function handleLike(postId, likeCountElement) {
async function handleLike(postId, likeCountElement, likeButton) {
try {
// check if user had already liked
const checkResponse = await fetch(`${API_BASE_URL}/${postId}/hasLiked?userId=${MOCK_USER_ID}`);
const hasLiked = await checkResponse.json();
const response = await fetch(`${API_BASE_URL}/${postId}/hasLiked`, {
method: 'GET',
credentials: 'include'
});
if (!response.ok) throw new Error('Failed to check like status');
const hasLiked = await response.json();
const method = hasLiked ? 'DELETE' : 'POST';
const response = await fetch(`${API_BASE_URL}/${postId}/like?userId=${MOCK_USER_ID}`, {
method: method
const likeResponse = await fetch(`${API_BASE_URL}/${postId}/like`, {
method: method,
credentials: 'include'
});
if (!likeResponse.ok) throw new Error('Failed to update like');
if (!response.ok) throw new Error('Failed to update like');
// update like count appropriately
const currentCount = parseInt(likeCountElement.textContent);
likeCountElement.textContent = hasLiked ? currentCount - 1 : currentCount + 1;
// change color to show they have liked already
const button = likeCountElement.closest('.like-button');
button.classList.toggle('liked', !hasLiked);
likeButton.classList.toggle('liked', !hasLiked);
} catch (error) {
console.error('Error updating like:', error);
alert('Error updating like. Please try again.');
}
}
// handling form submission whether update or post
postForm.addEventListener('submit', async (event) => {
event.preventDefault();
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment