Skip to content

Реализовать запросы и тестирование - #4

Merged
biscuitka merged 11 commits into
mainfrom
add-item-requests
Aug 18, 2023
Merged

biscuitka merged 11 commits into
mainfrom
add-item-requests

Conversation

@biscuitka

Copy link
Copy Markdown
Owner

No description provided.

BookingDtoOut getBooking(long userId, long bookingId);

List<BookingDtoOut> getAllBookingByUser(long userId, StateOfBooking stateOfBooking);
List<BookingDtoOut> getAllBookingByUser(long userId, StateOfBooking stateOfBooking, int from, int size);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вместо набора параметров лучше передать Pageable.
Аналогично ниже

List<Booking> bookings = bookingRepository.findByItemIdAndStatus(item.getId(), StatusOfBooking.APPROVED);
boolean isConflicting = !bookings.stream().allMatch(booking ->
!booking.getStart().isBefore(bookingDtoIn.getEnd()) || !booking.getEnd().isAfter(bookingDtoIn.getEnd())
booking.getStart().isAfter(bookingDtoIn.getEnd()) || booking.getEnd().isBefore(bookingDtoIn.getStart())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Пусть существующее бронирование происходит с 13:00 до 15:00, а новое с 15:00 до 17:00.
Будет ли пройдена валидация в таком случае?

this.httpStatus = httpStatus;
}

public HttpStatus getHttpStatus() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно использовать lombok вместо шаблонного кода.
Аналогично для остальных исключений

private Boolean available;
private Long requestId;

public ItemDtoRequested(Item item) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dto - это объект из внешнего мира, он ничего не должен знать о модели данных. Преобразование Item в Dto лучше сделать в маппере

ItemDto getById(long itemId, long userId);

List<ItemDto> getBySearch(String search);
List<ItemDto> getBySearch(String search, int from, int size);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вместо набора параметров лучше передать Pageable.
Аналогично ниже


@Override
public ItemDto createItem(ItemDto itemDto, Long userId) {
User owner = UserServiceImpl.getValidatedUser(userRepository, userId);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем передавать репозиторий, если в сервисе он уже есть?)

item.setOwner(owner);
Long requestId = itemDto.getRequestId();
if (requestId != null) {
ItemRequest request = ItemRequestServiceImpl.getValidatedRequest(requestRepository, requestId);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем передавать репозиторий, если в сервисе он уже есть?)
И вообще репозитории передавать в сервисы не нужно. Репозиторий - это вспомогательный объект для выполнения бизнес-функции. Это как прийти к стоматологу, принести все необходимые инструменты и сказать : "нужно вот в этом месте этим инструментом сделать такое-то действие"...)
Аналогично в остальных методах


RequestDtoWithItemsOut getById(long userId, long requestId);

List<RequestDtoWithItemsOut> getAllByOwner(long userId, int from, int size);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вместо набора параметров лучше передать Pageable.
Аналогично ниже


@Override
public RequestDtoOut createRequest(long userId, RequestDtoIn itemRequestDtoIn) {
User user = UserServiceImpl.getValidatedUser(userRepository, userId);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Передавать репозитории в другие сервисы не нужно

return dto;
}

public static RequestDtoWithItemsOut fromRequestToDtoWithItemsOut(ItemRequest request, List<Item> items) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нужно передать только те items, которые относятся к данному request, чтобы не перебирать лишние предметы в цикле на 36 строке

@biscuitka

biscuitka commented Aug 17, 2023 •

Copy link
Copy Markdown
Owner Author

забыла при создании сменить название коммита "написать тест на конструктор" 853cd1a, по факту там ломбок вместо геттеров и замена на pageable.

import ru.practicum.shareit.user.model.User;
import ru.practicum.shareit.user.repository.UserRepository;

public class EntityValidator {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Этот класс создает сильную связанность между классами, которые его используют. От таких классов лучше избавиться)
В сервисах можно явно использовать repositoru.findById(...).orElseThrow(...);
Или можно в репозитории добавить кастомные методы, которые бросят исключение, если объект не найден

@biscuitka
biscuitka merged commit 5c8798f into main Aug 18, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants