Skip to content

Make hw6#7

Open
yuuusha wants to merge 3 commits intomasterfrom
hw6
Open

Make hw6#7
yuuusha wants to merge 3 commits intomasterfrom
hw6

Conversation

@yuuusha
Copy link
Owner

@yuuusha yuuusha commented Mar 24, 2024

No description provided.

@github-actions
Copy link

github-actions bot commented Mar 24, 2024

Code Coverage

Overall Project 26.48% -14.3%
Files changed 8.43%

File Coverage
JdbcChatRepository.java 100% 🍏
ApplicationConfig.java 100% 🍏
JdbcAccessConfiguration.java 100% 🍏
JdbcTelegramChatService.java 79.73% 🍏
JdbcLinkRepository.java 73.85% 🍏
JdbcChatLinkRepository.java 64.52% 🍏
JdbcLinkService.java 20.75% 🍏
LinkEntityMapperImpl.java 13.64% -86.36%
LinkEntity.java 6.11% -93.89%
JpaChatService.java 0%
JpaLinkService.java 0%
TgChatEntity.java 0%
JooqAccessConfiguration.java 0%
JpaAccessConfiguration.java 0%

this.tgChats = new HashSet<>();
}

public Link toDto() {
Copy link

Choose a reason for hiding this comment

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

Для маппинга в дто и обратно принято использовать отдельные классы мапперы.
Хранить логическую часть преобразования в дто в самой сущности не очень здорово.
Когда есть маппер - он ответственен и тут все понятно, а сейчас нарушается Single Responsibility.
Чтобы не писать маппер вручную есть библиотеки MapStruct и ModelMapper. Рекомендую=)

Copy link

Choose a reason for hiding this comment

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

@repository противоречит условию задания 3

Copy link
Owner Author

Choose a reason for hiding this comment

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

Почему противоречит, в условии не запрещено использование @repository, укажите пожалуйста где это написано, возможно, я не до конца понял условие. Я нашел лишь запрет на использование @Service/@component.

Copy link

Choose a reason for hiding this comment

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

@repository - мета-аннотация, по существу тот же @component.
Не забудьте удалить любые аннотации связанные с жизненным циклом (@Service/@component) с базовых интерфейсов и имплементаций, создание имплементаций должно происходить в конфигурационном файле при помощи @bean
С учетом вышесказанного, странно ограничиваться только приведенными примерами аннотаций в скобках.

Copy link
Owner Author

Choose a reason for hiding this comment

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

@Keindel исправил

Copy link

Choose a reason for hiding this comment

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

equals, hashcode, tostring везде будут просто от Object?

Comment on lines +52 to +90
public LinkResponse addTrackingLink(URL link, Long chatId) {
TgChatEntity chat = chatRepository.findById(chatId).orElseThrow(() -> new ChatNotFoundException(chatId));
String host = link.getHost();
String domain = host.replaceAll("^(www\\.)?|\\.com$", "");
InfoSupplier infoSupplier = infoSuppliers.getSupplierByTypeHost(domain);
if (infoSupplier == null || !infoSupplier.isSupported(link)) {
throw new LinkIsNotSupportedException(link);
}

LinkInfo linkInfo = infoSupplier.fetchInfo(link);
if (linkInfo == null) {
throw new LinkIsNotSupportedException(link);
}

Optional<LinkEntity> linkOptional;
OffsetDateTime lastUpdate = OffsetDateTime.now();
if (!linkInfo.events().isEmpty()) {
lastUpdate = linkInfo.events().getFirst().lastUpdate();
}

LinkEntity linkEntity;
linkOptional = linkRepository.findByUrl(String.valueOf(linkInfo.url()));
if (linkOptional.isPresent()) {
linkEntity = linkOptional.get();
linkEntity.setLastUpdate(lastUpdate);
linkEntity.setLastCheck(OffsetDateTime.now());
linkEntity.setMetaInfo(linkInfo.metaInfo());
chat.addLink(linkEntity);
return new LinkResponse(linkEntity.getId(), link);
}
linkEntity = new LinkEntity(
String.valueOf(link),
lastUpdate,
OffsetDateTime.now(),
linkInfo.metaInfo()
);
chat.addLink(linkEntity);
return new LinkResponse(linkEntity.getId(), link);
}
Copy link

Choose a reason for hiding this comment

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

тяжеловато, давай разобьем на несколько методов?

Comment on lines +29 to +42
@Override
@Transactional
public void deleteChat(Long tgChatId) {
TgChatEntity tgChatEntity =
chatRepository.findById(tgChatId).orElseThrow(() -> new ChatNotFoundException(tgChatId));

for (LinkEntity link : tgChatEntity.getLinks()) {
tgChatEntity.removeLink(link);
if (link.getTgChats().isEmpty()) {
linkRepository.delete(link);
}
}
chatRepository.delete(tgChatEntity);
}
Copy link

Choose a reason for hiding this comment

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

На примере этого метода.
В зависимостях 2 репозитория :

    private final JpaChatRepository chatRepository;

    private final JpaLinkRepository linkRepository;

и далее в другом сервисе тоже.
Может получится лучше, если мы попробуем оставить 1 соответствующий репозиторий в зависимостях, а вместо других использовать сервисы. Чтобы сервисы были ответственны за обращение к своему репозиторию, любую логику, выброс и обработку ошибок. И не придется дублировать код работы с каждым репо в каждом методе.

Copy link
Owner Author

Choose a reason for hiding this comment

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

Один сервис зависит от другого, и я не могу создать бины в таком случае, поэтому я оставлю как есть

Comment on lines +29 to +32
jpa:
hibernate:
ddl-auto: validate
open-in-view: false
Copy link

Choose a reason for hiding this comment

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

еще можно добавить для удобства
show-sql: true
чтобы видеть какие sql запросы генерит hiber

@yuuusha yuuusha changed the base branch from hw5bonus to master April 27, 2024 07:52
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