-
Notifications
You must be signed in to change notification settings - Fork 0
Sprint 17 Stage 3 Comments solution #14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| # Комментарии — API (техническое задание) | ||
|
|
||
| Краткое описание: набор REST-эндпоинтов для управления комментариями. Три уровня доступа: | ||
| - Admin — администраторские операции (удаление комментария по его идентификатору). | ||
| - Private — операции пользователя над собственными комментариями (создать, изменить, удалить, получить все свои комментарии). | ||
| - Public — публичный доступ (просмотр комментариев конкретного события). | ||
|
|
||
| --- | ||
|
|
||
| ## AdminCommentController | ||
| Цель: операции управления всеми комментариями. | ||
|
|
||
| - DELETE `/admin/comments/{commentId}` | ||
| - Описание: удалить комментарий (жёсткое удаление) по его идентификатору. | ||
| - Ограничения: без модерации комментариев. | ||
| - Права: только админ. | ||
| - Ответ: `204 No Content` при успехе. | ||
|
|
||
| --- | ||
|
|
||
| ## PrivateCommentController | ||
| Цель: пользовательские операции над собственными комментариями. | ||
|
|
||
| - POST `/users/{userId}/comments/{eventId}` | ||
| - Описание: создать новый комментарий от имени пользователя `userId`. | ||
| - Ограничения: длина комментария 5000 символов, проверка существования идентификаторов события и пользователя. | ||
| - Права: только аутентифицированный пользователь. | ||
| - Ответ: `201 Created` с созданным объектом. | ||
|
|
||
| - PATCH `/users/{userId}/comments/{eventId}/{commentId}` | ||
| - Описание: обновить собственный комментарий. | ||
| - Ограничения: длина комментария 5000 символов, проверка существования идентификаторов комментария, события и пользователя. | ||
| - Права: только автор комментария. | ||
| - Ответ: обновлённый объект комментария. | ||
|
|
||
| - DELETE `/users/{userId}/comments/{commentId}` | ||
| - Описание: удалить собственный комментарий (жёсткое удаление). | ||
| - Ограничения: проверка существования идентификаторов комментария и пользователя. | ||
| - Права: только автор комментария. | ||
| - Ответ: `204 No Content`. | ||
|
|
||
| - GET `/users/{userId}/comments` | ||
| - Описание: получить список собственных комментариев. | ||
| - Ограничения: организовать пагинацию (по умолчанию по 10 комментариев на странице). | ||
| - Права: только аутентифицированный пользователь. | ||
| - Ответ: список комментариев. | ||
|
|
||
| --- | ||
|
|
||
| ## PublicCommentController | ||
| Цель: публичный просмотр комментариев. | ||
|
|
||
| - GET `/comments/event/{eventId}` | ||
| - Описание: получить публичный список комментариев к событию. | ||
| - Ограничения: организовать пагинацию (по умолчанию по 10 комментариев на странице). | ||
| - Доступ: публичный (без авторизации). | ||
| - Ответ: список публичных комментариев. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
6 changes: 6 additions & 0 deletions
6
main-service/src/main/java/ru/practicum/category/repository/CategoryRepository.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,14 +1,20 @@ | ||
| package ru.practicum.category.repository; | ||
|
|
||
| import org.springframework.data.domain.Pageable; | ||
| import org.springframework.data.jpa.repository.JpaRepository; | ||
| import org.springframework.data.jpa.repository.Query; | ||
| import org.springframework.data.repository.query.Param; | ||
| import ru.practicum.category.model.Category; | ||
|
|
||
| import java.util.List; | ||
| import java.util.Optional; | ||
|
|
||
| public interface CategoryRepository extends JpaRepository<Category, Long> { | ||
|
|
||
| Optional<Category> findByName(@Param("name") String name); | ||
|
|
||
| Optional<Category> findByNameAndIdNot(@Param("name") String name, @Param("id") Long id); | ||
|
|
||
| @Query("SELECT c FROM Category c") | ||
| List<Category> findAllList(Pageable pageable); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
25 changes: 25 additions & 0 deletions
25
main-service/src/main/java/ru/practicum/comment/controller/AdminCommentController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| package ru.practicum.comment.controller; | ||
|
|
||
| import jakarta.validation.constraints.Positive; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.http.HttpStatus; | ||
| import org.springframework.validation.annotation.Validated; | ||
| import org.springframework.web.bind.annotation.*; | ||
| import ru.practicum.comment.service.CommentService; | ||
|
|
||
| @Slf4j | ||
| @Validated | ||
| @RestController | ||
| @RequestMapping("/admin/comments") | ||
| @RequiredArgsConstructor | ||
| public class AdminCommentController { | ||
| private final CommentService commentService; | ||
|
|
||
| @DeleteMapping("/{commentId}") | ||
| @ResponseStatus(HttpStatus.NO_CONTENT) | ||
| public void deleteCommentAdmin(@PathVariable @Positive Long commentId) { | ||
| log.debug("Controller: deleteCommentAdmin commentId={}", commentId); | ||
| commentService.deleteCommentAdmin(commentId); | ||
| } | ||
| } |
65 changes: 65 additions & 0 deletions
65
main-service/src/main/java/ru/practicum/comment/controller/PrivateCommentController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| package ru.practicum.comment.controller; | ||
|
|
||
| import jakarta.validation.Valid; | ||
| import jakarta.validation.constraints.Positive; | ||
| import jakarta.validation.constraints.PositiveOrZero; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.data.domain.PageRequest; | ||
| import org.springframework.http.HttpStatus; | ||
| import org.springframework.validation.annotation.Validated; | ||
| import org.springframework.web.bind.annotation.*; | ||
| import ru.practicum.comment.dto.CommentDto; | ||
| import ru.practicum.comment.dto.NewCommentDto; | ||
| import ru.practicum.comment.dto.UpdateCommentDto; | ||
| import ru.practicum.comment.service.CommentService; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| @Slf4j | ||
| @Validated | ||
| @RestController | ||
| @RequestMapping("/users/{userId}/comments") | ||
| @RequiredArgsConstructor | ||
| public class PrivateCommentController { | ||
| private final CommentService commentService; | ||
|
|
||
| @PostMapping("/{eventId}") | ||
| @ResponseStatus(HttpStatus.CREATED) | ||
| public CommentDto createComment(@PathVariable @Positive Long userId, | ||
|
Naz1anmak marked this conversation as resolved.
|
||
| @PathVariable @Positive Long eventId, | ||
| @RequestBody @Valid NewCommentDto newCommentDto | ||
| ) { | ||
| log.debug("Controller: createComment userId={}, eventId={}, data={}", userId, eventId, newCommentDto); | ||
| return commentService.createComment(userId, eventId, newCommentDto); | ||
| } | ||
|
|
||
| @PatchMapping("/{eventId}/{commentId}") | ||
| public CommentDto updateComment(@PathVariable @Positive Long userId, | ||
| @PathVariable @Positive Long eventId, | ||
| @PathVariable @Positive Long commentId, | ||
| @RequestBody @Valid UpdateCommentDto updateCommentDto | ||
| ) { | ||
| log.debug("Controller: updateComment userId={}, eventId={}, commentId={}, data={}", userId, eventId, commentId, | ||
| updateCommentDto); | ||
| return commentService.updateComment(userId, eventId, commentId, updateCommentDto); | ||
| } | ||
|
|
||
| @DeleteMapping("/{commentId}") | ||
| @ResponseStatus(HttpStatus.NO_CONTENT) | ||
| public void deleteComment(@PathVariable @Positive Long userId, | ||
| @PathVariable @Positive Long commentId | ||
| ) { | ||
| log.debug("Controller: deleteComment userId={}, commentId={}", userId, commentId); | ||
| commentService.deleteComment(userId, commentId); | ||
| } | ||
|
|
||
| @GetMapping | ||
| public List<CommentDto> getCommentsForUser(@PathVariable @Positive Long userId, | ||
| @RequestParam(defaultValue = "0") @PositiveOrZero Integer from, | ||
| @RequestParam(defaultValue = "10") @Positive Integer size | ||
| ) { | ||
| log.debug("Controller: getCommentsForUser userId={}, from={}, size={}", userId, from, size); | ||
| return commentService.getCommentsForUser(userId, PageRequest.of(from / size, size)); | ||
| } | ||
| } | ||
31 changes: 31 additions & 0 deletions
31
main-service/src/main/java/ru/practicum/comment/controller/PublicCommentController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| package ru.practicum.comment.controller; | ||
|
|
||
| import jakarta.validation.constraints.Positive; | ||
| import jakarta.validation.constraints.PositiveOrZero; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.data.domain.PageRequest; | ||
| import org.springframework.validation.annotation.Validated; | ||
| import org.springframework.web.bind.annotation.*; | ||
| import ru.practicum.comment.dto.CommentDto; | ||
| import ru.practicum.comment.service.CommentService; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| @Slf4j | ||
| @Validated | ||
| @RestController | ||
| @RequestMapping("/comments") | ||
| @RequiredArgsConstructor | ||
| public class PublicCommentController { | ||
| private final CommentService commentService; | ||
|
|
||
| @GetMapping("/event/{eventId}") | ||
| public List<CommentDto> getCommentsForEvent(@PathVariable @Positive Long eventId, | ||
| @RequestParam(defaultValue = "0") @PositiveOrZero Integer from, | ||
| @RequestParam(defaultValue = "10") @Positive Integer size | ||
| ) { | ||
| log.debug("Controller: getCommentsForEvent eventId={}, from={}, size={}", eventId, from, size); | ||
| return commentService.getCommentsForEvent(eventId, PageRequest.of(from / size, size)); | ||
| } | ||
| } |
21 changes: 21 additions & 0 deletions
21
main-service/src/main/java/ru/practicum/comment/dto/CommentDto.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| package ru.practicum.comment.dto; | ||
|
|
||
| import com.fasterxml.jackson.annotation.JsonFormat; | ||
|
|
||
| import java.time.LocalDateTime; | ||
|
|
||
| import static ru.practicum.constants.DateTimeConstants.DATE_TIME_PATTERN; | ||
|
|
||
| public record CommentDto( | ||
| Long id, | ||
|
|
||
| String text, | ||
|
|
||
| Long userId, | ||
|
|
||
| Long eventId, | ||
|
|
||
| @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DATE_TIME_PATTERN) | ||
| LocalDateTime createdDate | ||
| ) { | ||
| } |
11 changes: 11 additions & 0 deletions
11
main-service/src/main/java/ru/practicum/comment/dto/NewCommentDto.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| package ru.practicum.comment.dto; | ||
|
|
||
| import jakarta.validation.constraints.NotBlank; | ||
| import jakarta.validation.constraints.Size; | ||
|
|
||
| public record NewCommentDto( | ||
| @NotBlank(message = "Комментарий не может быть пустым") | ||
| @Size(min = 1, max = 5000, message = "Комментарий должен содержать от {min} до {max} символов") | ||
| String text | ||
| ) { | ||
| } |
11 changes: 11 additions & 0 deletions
11
main-service/src/main/java/ru/practicum/comment/dto/UpdateCommentDto.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| package ru.practicum.comment.dto; | ||
|
|
||
| import jakarta.validation.constraints.NotBlank; | ||
| import jakarta.validation.constraints.Size; | ||
|
|
||
| public record UpdateCommentDto( | ||
| @NotBlank(message = "Комментарий не может быть пустым") | ||
| @Size(min = 1, max = 5000, message = "Комментарий должен содержать от {min} до {max} символов") | ||
| String text | ||
| ) { | ||
| } |
26 changes: 26 additions & 0 deletions
26
main-service/src/main/java/ru/practicum/comment/mapper/CommentMapper.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| package ru.practicum.comment.mapper; | ||
|
|
||
| import org.mapstruct.*; | ||
| import ru.practicum.comment.dto.CommentDto; | ||
| import ru.practicum.comment.dto.NewCommentDto; | ||
| import ru.practicum.comment.dto.UpdateCommentDto; | ||
| import ru.practicum.comment.model.Comment; | ||
| import ru.practicum.event.model.Event; | ||
| import ru.practicum.user.model.User; | ||
|
|
||
| @Mapper(componentModel = "spring") | ||
| public interface CommentMapper { | ||
| @Mapping(target = "id", ignore = true) | ||
| @Mapping(target = "createdDate", ignore = true) | ||
| Comment toComment(NewCommentDto newCommentDto, User user, Event event); | ||
|
|
||
| @Mapping(target = "userId", source = "user.id") | ||
| @Mapping(target = "eventId", source = "event.id") | ||
| CommentDto toDto(Comment comment); | ||
|
|
||
| @Mapping(target = "id", ignore = true) | ||
| @Mapping(target = "user", ignore = true) | ||
| @Mapping(target = "event", ignore = true) | ||
| @Mapping(target = "createdDate", ignore = true) | ||
| void updateCommentFromDto(UpdateCommentDto dto, @MappingTarget Comment comment); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.