-
Notifications
You must be signed in to change notification settings - Fork 0
feat: Реализация e-commerce платформы (Store, Cart, Warehouse) #10
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
Conversation
Standardized all Java module names to follow the pattern
`{root}.{subsystem}.{module}`.
…ntions To improve maintainability and align the module with Domain-Driven Design principles, the package structure has been reorganized into distinct layers. This separates core domain logic from application and infrastructure concerns, establishing a cleaner architecture. The new packages include `domain`, `application`, `infrastructure`, and `presentation`.
…reporting The ApiErrorDto has been completely redesigned to provide useful, consistent, and safe error information to API clients. The previous implementation was a thin wrapper around Throwable, which leaked internal details. The new structure includes key contextual fields like timestamp and request path while explicitly preventing sensitive information, such as stack traces, from being exposed.
To align with the requirements of the CI environment, the persistence strategy has been completely refactored. The key changes are: - Switched from a single-database, multi-schema model to a dedicated database-per-service model. - Removed per-service database users in favor of a single user. - Eliminated the manual SQL initialization script and now rely entirely on Hibernate's `ddl-auto` for schema generation. - As a consequence of using `ddl-auto`, all native PostgreSQL enums have been changed to be stored as Strings.
kesch9
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Несколько комментариев
| @@ -0,0 +1,53 @@ | |||
| server: | |||
| port: 8087 | |||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
порты должны быть указаны 0
так сервис будет работать на свободному порту
server:
port: 0
В остальных сервисах также
Когда работают несколько инстансов, вы не сможете их запустить если будет жестко указан порт
|
|
||
| management: | ||
| server: | ||
| port: 8087 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
При указании port 0, указывать здесь не нужно, будет работать на том порту, на котором работает сервис
|
|
||
| logging: | ||
| level: | ||
| ru.yandex.practicum: DEBUG |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
DEBUG используется при отладке, на сдачу надо поднимать до INFO
|
|
||
| @AutoConfiguration | ||
| @ComponentScan("ru.yandex.practicum.smarthometech.commerce.api.mapper") | ||
| public class InteractionApiModuleAutoConfiguration { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Не совсем понятно зачем этот класс нужен в api
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Да, в данной версии API модуля уже нет мапперов, так что этот класс и правда лишний.
| @JoinColumn(name = "shopping_cart_id", nullable = false) | ||
| private ShoppingCart shoppingCart; | ||
|
|
||
| @NotNull |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Валидационные аннотации для Entity избыточны, т.к. работаем c Dto и они поступают от клиентов. Для Entity достаточно указывать ограничения в Column
|
|
||
| @Override | ||
| public int hashCode() { | ||
| return Objects.hash(shoppingCart, productId); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Использовать shoppingCart в качестве расчета hashcode и equals не оптимально, т.к. это ManyToOne
В целом не обязательно переопределять equals и hashCode
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Согласен, использовать весь shoppingCart здесь не рационально. Т.к. я использую Set<CartItem>, мне нужен хороший hashCode(). Учитывая это, я переработал equals() и hashCode() — теперь они основываются только на ID у shoppingCart. ID у прокси-объектов Hibernate всегда инициализированы, поэтому это не вызовет проблем из-за lazy loading'а.
| @Override | ||
| public ShoppingCart save(ShoppingCart cart) { | ||
| return jpaRepository.saveAndFlush(cart); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Применение адаптеров по моему мнению избыточно
Минусы:
Избыточность: Если интерфейс ShoppingCartRepository и JpaShoppingCartRepositoryInterface имеют много схожих методов, это может привести к избыточности кода.
Потенциальные накладные расходы: Если адаптер не добавляет значительной логики, его использование может быть излишним.
В вашей реализации можно было использовать просто repository
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Мне хотелось реализовать более чистую DDD архитектуру, где domain полностью независим от используемых технологий (JPA) и деталей реализации (saveAndFlush()). Изначально я пытался использовать только два интерфейса — "чистый" в domain и JPA в infrastructure, — но это вызывало проблемы, например, при попытке перегрузить save(), который уже является частью CrudRepository.
Я понимаю, что это компромисс, который даёт более чистые абстракции, но усложняет код. Если нужно, я упрощу это до одного JPA интерфейса в domain.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Оставьте, для обучение самое подходящее место, оставил комментарий просто указать, что adapter будет избыточен для такой простой логики.
…ct response Replaced declarative @transactional with programmatic TransactionTemplate for the product creation logic. This change was necessary to resolve a race condition in the CI tests where a product was being fetched immediately after creation and was not yet visible. Using TransactionTemplate ensures the database commit is complete before the HTTP response is sent.
kesch9
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Approve
Этот Pull Request добавляет базовую функциональность интернет-магазина в виде трёх новых микросервисов в модуле
commerce:shopping-store,shopping-cartиwarehouse.Ключевые архитектурные решения и реализованная функциональность:
Разделение по принципу "Database per Service":
ddl-auto: update), что потребовало отказа от нативныхENUM-типов PostgreSQL в пользу их хранения в видеString.Централизованная конфигурация и Service Discovery:
Синхронное взаимодействие через Feign:
shopping-cart->warehouseдля проверки остатков) реализована с помощью декларативных Feign-клиентов.interaction-apiдля обеспечения консистентности.Отказоустойчивость с помощью Circuit Breaker:
WarehouseClientв сервисеshopping-cart.Архитектура сервисов:
ApiErrorDtoбыла полностью переработана для предоставления клиентам полезной, структурированной информации (timestamp, path, errorCode) без утечки внутренних деталей, таких как stack trace.Адаптация под CI-окружение:
quantityStateвshopping-store) и конфигураций был адаптирован для полного соответствия с требованиями, обнаруженными в ходе интеграционного тестирования в CI.