Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,86 @@ Slices on this layer represent concepts from the real world that the project is

An entity slice might contain the data storage (`📁 model`), data validation schemas (`📁 model`), entity-related API request functions (`📁 api`), as well as the visual representation of this entity in the interface (`📁 ui`). The visual representation doesn't have to produce a complete UI block — it is primarily meant to reuse the same appearance across several pages in the app, and different business logic may be attached to it through props or slots.

#### When to create an Entity

An important principle for effective use of the Entities layer: not everything should be an entity. Don't create entities "just in case." Start with local code in Pages layers and refactor to Entity only when there's real necessity (reuse or complexity).

This approach aligns with:
- YAGNI (You Aren't Gonna Need It)
- Pragmatism in development
- FSD 2.1 philosophy (avoid premature decomposition)

Decision tree:

┌──────────────────────────────────┐
│ Used in one place only? │
└────────────┬─────────────────────┘
┌─────┴─────┐
│ │
YES NO
│ │
▼ ▼
┌─────────────┐ ┌──────────────────┐
│ Keep in │ │ Check │
│ pages/ │ │ complexity │
└─────────────┘ └────────┬─────────┘
┌────────────────────┐
│ Simple CRUD only? │
└────────┬───────────┘
┌─────┴─────┐
│ │
YES NO
│ │
▼ ▼
┌──────────┐ ┌─────────┐
│ API + │ │ Entity │
│ types │ │ (rules │
│ (shared) │ │ 2-4) │
└──────────┘ └─────────┘

Rules for creating Entities:

0. Locality (Page)
- Used in one place only
- Simple logic
- No signs of reuse
→ Keep locally, DON'T create Entity

1. API + Types (shared)
- Used in 2+ places
- Types and CRUD operations only
- No business logic
→ shared/api

2. Entity with computed properties
- Used in 2+ places
- Has computed properties
- Formatting, simple business rules
→ entities/*/model/*.ts

3. Entity with aggregation
- Combines data from different sources
- Data enrichment
→ entities/*/model/*.ts

4. Stateful Entity
- Collection management
- Filtering, sorting, caching
→ entities/*/model/*.ts

5. Feature (not Entity)
- Cross-entity logic
- Business scenarios, validation with limits
→ features/

Golden rule: Local → shared/api → Entity (when needed)

Key point: The marker for creating an Entity is not simply "used in two places," but a combination of reuse and the presence of business logic. If code is reused but only contains types and simple CRUD operations, shared/api is sufficient.

#### Entity relationships

Entities in FSD are slices, and by default, slices cannot know about each other. In real life, however, entities often interact with each other, and sometimes one entity owns or contains other entities. Because of that, the business logic of these interactions is preferably kept in higher layers, like Features or Pages.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,88 @@ import useBaseUrl from "@docusaurus/useBaseUrl";

Слайс сущности может содержать хранилище данных (`📁 model`), схемы валидации данных (`📁 model`), функции запросов API, связанные с сущностями (`📁 api`), а также визуальное представление этой сущности в интерфейсе (`📁 ui`). Это визуальное представление не обязательно должно создавать полный блок пользовательского интерфейса — оно в первую очередь предназначено для переиспользования одного и того же внешнего вида на нескольких страницах приложения, и к нему может быть присоединена различная бизнес-логика через пропcы или слоты.

#### Когда создавать Entity

Важный принцип эффективного использования слоя Entities: не все должно быть сущностью. Не создавайте сущности "на всякий случай". Начинайте с локального кода в слоях Pages и выполняйте рефакторинг в Entity только при реальной необходимости (переиспользование или сложность).

Этот подход согласуется с:
- YAGNI (You Aren't Gonna Need It)
- Прагматизмом в разработке
- Философией FSD 2.1 (избегать преждевременной декомпозиции)

Дерево принятия решений:

┌──────────────────────────────────┐
│ Используется только в одном │
│ месте? │
└────────────┬─────────────────────┘
┌─────┴─────┐
│ │
ДА НЕТ
│ │
▼ ▼
┌─────────────┐ ┌──────────────────┐
│ Держи в │ │ Проверь │
│ pages/ │ │ сложность │
└─────────────┘ └────────┬─────────┘
┌────────────────────┐
│ Только простой │
│ CRUD? │
└────────┬───────────┘
┌─────┴─────┐
│ │
ДА НЕТ
│ │
▼ ▼
┌──────────┐ ┌─────────┐
│ API + │ │ Entity │
│ типы │ │ (правила│
│ (shared) │ │ 2-4) │
└──────────┘ └─────────┘

Правила создания Entity:

0. Локальность (Page/Feature)
- Используется только в одном месте
- Простая логика
- Нет признаков переиспользования
→ Держите локально, НЕ создавайте Entity

1. API + Типы (shared)
- Используется в 2+ местах
- Только типы и CRUD-операции
- Нет бизнес-логики
→ shared/api

2. Entity с вычисляемыми свойствами
- Используется в 2+ местах
- Есть вычисляемые свойства (computed)
- Форматирование, простые бизнес-правила
→ entities/*/model/*.ts

3. Entity с агрегацией
- Объединяет данные из разных источников
- Обогащение модели данными
→ entities/*/model/*.ts

4. Stateful Entity
- Управление коллекцией
- Фильтрация, сортировка, кеширование
→ entities/*/model/*.ts

5. Feature (не Entity)
- Кросс-entity логика
- Бизнес-сценарии, валидация с лимитами
→ features/

Золотое правило: Локально → shared/api → Entity (при необходимости)

Ключевой момент: Маркером для создания Entity является не просто "используется в двух местах", а комбинация переиспользования и наличия бизнес-логики. Если код переиспользуется, но содержит только типы и простые CRUD-операции, достаточно shared/api.

#### Связи между сущностями

Сущности в FSD являются слайсами, и по умолчанию слайсы не могут знать друг о друге. Однако в реальной жизни сущности часто взаимодействуют друг с другом, и иногда одна сущность владеет или содержит другие сущности. Из-за этого бизнес-логику этих взаимодействий лучше всего хранить на более высоких уровнях, таких как Features или Pages.
Expand Down