Skip to content

Commit

Permalink
first commit for Comment Fuctionality
Browse files Browse the repository at this point in the history
  • Loading branch information
daniel-pohl committed Jun 10, 2024
1 parent cef636a commit 03c90f7
Show file tree
Hide file tree
Showing 6 changed files with 117 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.neuefische.team2.backend.restaurant;

import com.neuefische.team2.backend.restaurant.domain.NewCommentDTO;
import com.neuefische.team2.backend.restaurant.domain.NewRestaurantDTO;
import com.neuefische.team2.backend.exceptions.ResourceNotFoundException;
import com.neuefische.team2.backend.restaurant.domain.Restaurant;
Expand All @@ -12,6 +13,7 @@
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
Expand All @@ -37,7 +39,7 @@ Restaurant getRestaurantById(@PathVariable @Valid String id) {
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Restaurant addRestaurant(@RequestBody @Valid NewRestaurantDTO newRestaurantDTO) {
Restaurant restaurant = new Restaurant(null, newRestaurantDTO.title(), newRestaurantDTO.city());
Restaurant restaurant = new Restaurant(null, newRestaurantDTO.title(), newRestaurantDTO.city(), new ArrayList<>());
return restaurantService.addRestaurant(restaurant);
}

Expand All @@ -50,4 +52,16 @@ Restaurant putRestaurant(@Valid @RequestBody NewRestaurantDTO newRestaurantDTO,
void deleteRestaurant(@PathVariable String id) {
restaurantService.deleteRestaurant(id);
}


@PostMapping("/{id}/comments")
public Restaurant addComment(@PathVariable String id, @RequestBody NewCommentDTO comment) {
return restaurantService.addCommentToRestaurant(id, comment.text());
}


@GetMapping("/{id}/comments")
public List<Restaurant.Comment> getComments(@PathVariable String id) {
return restaurantService.getCommentsForRestaurant(id);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
Expand Down Expand Up @@ -44,12 +45,13 @@ public Restaurant addRestaurant(Restaurant restaurant) {

public Restaurant updateRestaurant(NewRestaurantDTO updatedRestaurantDTO, String id) throws ResourceNotFoundException {
logger.info("Trying to update restaurant with ID {}", id);

Restaurant existingRestaurant = this.findRestaurantById(id);
this.findRestaurantById(id);
Restaurant updatedRestaurant = new Restaurant(
id,
updatedRestaurantDTO.title().trim(),
updatedRestaurantDTO.city().trim()
updatedRestaurantDTO.city().trim(),
existingRestaurant.comments()
);
Restaurant savedRestaurant = restaurantRepository.save(updatedRestaurant);

Expand All @@ -61,4 +63,29 @@ public void deleteRestaurant(String id) {
this.findRestaurantById(id);
restaurantRepository.deleteById(id);
}

public Restaurant addCommentToRestaurant(String id, String commentText) throws ResourceNotFoundException {
logger.info("Trying to add comment to restaurant with ID {}", id);

Restaurant restaurant = this.findRestaurantById(id);
List<Restaurant.Comment> updatedComments = new ArrayList<>(restaurant.comments() != null ? restaurant.comments() : new ArrayList<>());
Restaurant.Comment comment = new Restaurant.Comment(commentText, System.currentTimeMillis());
updatedComments.add(comment);

Restaurant updatedRestaurant = new Restaurant(
restaurant.id(),
restaurant.title(),
restaurant.city(),
updatedComments
);
return restaurantRepository.save(updatedRestaurant);
}


public List<Restaurant.Comment> getCommentsForRestaurant(String id) throws ResourceNotFoundException {
logger.info("Trying to get comments for restaurant with ID {}", id);

Restaurant restaurant = this.findRestaurantById(id);
return restaurant.comments();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.neuefische.team2.backend.restaurant.domain;

public record NewCommentDTO(
String text

) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import jakarta.validation.constraints.NotBlank;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.List;

@Document("restaurants")
public record Restaurant(
@Id
Expand All @@ -13,6 +15,11 @@ public record Restaurant(
String title,

@NotBlank(message = "Restaurant-Stadt muss vorhanden sein.")
String city
String city,
List<Comment> comments
) {
public record Comment(
String text,
long createdAt
) {}
}
56 changes: 56 additions & 0 deletions frontend/src/components/Comments/CommentsSection.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { useState, useEffect } from "react";
import axios from "axios";

type CommentsSectionProps = {
restaurantId: string;
};

function CommentsSection({ restaurantId }: CommentsSectionProps) {
const [comments, setComments] = useState<{ text: string }[]>([]);
const [newComment, setNewComment] = useState<{ text: string }>({ text: "" });

useEffect(() => {
axios
.get(`/api/restaurants/${restaurantId}/comments`)
.then((response) => {
setComments(response.data);
})
.catch((error) => {
console.error("There was an error fetching the comments!", error);
});
}, [restaurantId]);

const handleAddComment = () => {
axios
.post(`/api/restaurants/${restaurantId}/comments`, newComment)
.then((response) => {
setComments(response.data.comments);
setNewComment({ text: "" });
})
.catch((error) => {
console.error("There was an error adding the comment!", error);
});
};

return (
<div>
<h3>Comments</h3>
<input
type="text"
value={newComment.text}
onChange={(e) => setNewComment({ text: e.target.value })}
placeholder="Add a comment"
/>
<button onClick={handleAddComment}>Add Comment</button>
<ul>
{comments.length > 0 ? (
comments.map((comment, index) => <li key={index}>{comment.text}</li>)
) : (
<li>No comments available.</li>
)}
</ul>
</div>
);
}

export default CommentsSection;
2 changes: 2 additions & 0 deletions frontend/src/pages/ViewRestaurantPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { logtail } from "../logger.ts";
import AlertBox from "../components/AlertBox/AlertBox.tsx";
import { mutate } from "swr";
import { RestaurantType } from "../model/Restaurant.ts";
import CommentsSection from "../components/Comments/CommentsSection.tsx";

export default function ViewRestaurantPage() {
const navigate = useNavigate();
Expand Down Expand Up @@ -78,6 +79,7 @@ export default function ViewRestaurantPage() {
>
Delete
</Button>
<CommentsSection restaurantId={id} />
</DefaultPageTemplate>
);
}

0 comments on commit 03c90f7

Please sign in to comment.