К основному содержанию
скилл CX Codex

clean-architecture · giuseppe-trisciuoglio, developer-kit-typescript — скилл для Claude Code: архитектура NestJS

Помогает проектировать слои Clean Architecture, DDD и Hexagonal Architecture в приложениях NestJS на TypeScript. Пригодится при создании доменной модели или разборе тесно связанного MVC-кода.

MIT ★ 372 обновлён 2026-09-10

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add giuseppe-trisciuoglio/developer-kit
/plugin install developer-kit-typescript@developer-kit
Открыть на GitHub

Что делает clean-architecture

Скилл предлагает структуру проекта с доменным, прикладным и инфраструктурным слоями, а также адаптерами. Он разбирает сущности, объекты-значения, агрегаты, доменные события и порты репозиториев. Зависимости направляются к домену, а бизнес-правила остаются отдельно от кода NestJS и базы данных.

Для прикладного слоя скилл описывает сценарии использования с DTO и методом execute; реализации портов размещаются в адаптерах. Также он разбирает внедрение зависимостей через модули NestJS, проверку инвариантов и место транзакций. Доменную логику предлагается тестировать без тестового модуля NestJS, поэтому доменные сущности не должны зависеть от фреймворка.

Какие задачи решает

  • разложить NestJS-проект на доменный, прикладной и инфраструктурный слои
  • описать сущности и объекты-значения с бизнес-правилами
  • выделить порты и подключить к ним адаптеры
  • перенести бизнес-сценарии в отдельные сценарии использования
  • отделить доменную логику от NestJS и TypeORM

Примеры запросов агенту

  • Перестрой структуру этого NestJS-проекта по Clean Architecture и покажи, какие файлы отнести к каждому слою.
  • Спроектируй доменную модель заказа с агрегатом, объектами-значениями и доменными событиями.
  • Создай сценарий использования с портом репозитория и адаптером для TypeORM.

Как установить clean-architecture

1Через маркетплейс плагинов

/plugin marketplace add giuseppe-trisciuoglio/developer-kit
/plugin install developer-kit-typescript@developer-kit

Команда ставит плагин developer-kit-typescript целиком, со всеми его скиллами

2Через Skills CLI (Vercel)

npx skills add giuseppe-trisciuoglio/developer-kit --skill clean-architecture -a claude-code

3Вручную: положить файлы

~/.claude/skills/clean-architecture/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/clean-architecture/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о clean-architecture

Как установить clean-architecture в Claude Code?

Выполните /plugin marketplace add giuseppe-trisciuoglio/developer-kit? Нет: команда должна быть без пробелов внутри кода: /plugin marketplace add giuseppe-trisciuoglio/developer-kit, затем /plugin install developer-kit-typescript@developer-kit.

Что делает clean-architecture?

Скилл помогает строить приложения NestJS на TypeScript по Clean Architecture, DDD и Ports & Adapters. Он описывает слои, доменные модели, сценарии использования и адаптеры.

Должны ли доменные сущности зависеть от NestJS?

Нет. По описанному правилу доменный слой не зависит от NestJS, TypeORM или HTTP; внедрение зависимостей применяется во внешних слоях.

Исходный текст

SKILL.md · MIT
---
name: clean-architecture
description: Provides implementation patterns for Clean Architecture, Domain-Driven Design (DDD), and Hexagonal Architecture (Ports & Adapters) in NestJS/TypeScript applications. Use when structuring complex backend systems, designing domain layers with entities/value objects/aggregates, implementing ports and adapters, creating use cases, or refactoring from anemic models to rich domain models with dependency inversion.
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
---

# Clean Architecture, DDD & Hexagonal Architecture for NestJS

## Overview

This skill provides comprehensive guidance for implementing Clean Architecture, Domain-Driven Design (DDD), and Hexagonal Architecture patterns in NestJS/TypeScript applications. It covers the architectural layers, tactical patterns, and practical implementation examples for building maintainable, testable, and loosely-coupled backend systems.

## When to Use

- Architecting complex NestJS applications with long-term maintainability
- Refactoring from tightly-coupled MVC to layered architecture
- Implementing rich domain models with business logic encapsulation
- Designing testable systems with swappable infrastructure
- Creating microservices with clear bounded contexts
- Separating business rules from framework code
- Implementing event-driven architectures with domain events

## Instructions

### 1. Understand the Architectural Layers

Clean Architecture organizes code into concentric layers where dependencies flow inward. Inner layers have no knowledge of outer layers:

```
+-------------------------------------+
|  Infrastructure (Frameworks, DB)    |  Outer layer - volatile
+-------------------------------------+
|  Adapters (Controllers, Repositories)|  Interface adapters
+-------------------------------------+
|  Application (Use Cases)            |  Business rules
+-------------------------------------+
|  Domain (Entities, Value Objects)   |  Core - most stable
+-------------------------------------+
```

The Hexagonal Architecture (Ports & Adapters) pattern complements this:
- **Ports**: Interfaces defining what the application needs
- **Adapters**: Concrete implementations of ports
- **Domain Core**: Pure business logic with zero dependencies

### 2. Learn DDD Tactical Patterns

Apply these patterns in your domain layer:
- **Entities**: Objects with identity and lifecycle
- **Value Objects**: Immutable, defined by attributes
- **Aggregates**: Consistency boundaries with aggregate roots
- **Domain Events**: Capture state changes
- **Repositories**: Abstract data access for aggregates

### 3. Organize Your Project Structure

Structure your NestJS project following Clean Architecture principles:

```
src/
+-- domain/                    # Inner layer - no external deps
|   +-- entities/              # Domain entities
|   +-- value-objects/         # Immutable value objects
|   +-- aggregates/            # Aggregate roots
|   +-- events/                # Domain events
|   +-- repositories/          # Repository interfaces (ports)
|   +-- services/              # Domain services
+-- application/               # Use cases - orchestration
|   +-- use-cases/             # Individual use cases
|   +-- ports/                 # Input/output ports
|   +-- dto/                   # Application DTOs
|   +-- services/              # Application services
+-- infrastructure/            # External concerns
|   +-- database/              # ORM config, migrations
|   +-- http/                  # HTTP clients
|   +-- messaging/             # Message queues
+-- adapters/                  # Interface adapters
    +-- http/                  # Controllers, presenters
    +-- persistence/           # Repository implementations
    +-- external/              # External service adapters
```

### 4. Implement the Domain Layer

Create pure domain objects with no external dependencies:

1. **Value Objects**: Immutable objects validated at construction
2. **Entities**: Objects with identity containing business logic
3. **Aggregates**: Consistency boundaries protecting invariants
4. **Repository Ports**: Interfaces defining data access contracts

### 5. Implement the Application Layer

Create use cases that orchestrate business logic:

1. Define input/output DTOs for each use case
2. Inject repository ports via constructor
3. Implement business workflows in the `execute` method
4. Keep use cases focused on a single responsibility

### 6. Implement Adapters

Create concrete implementations of ports:

1. **Persistence Adapters**: Map domain objects to/from ORM entities
2. **HTTP Adapters**: Controllers that transform requests to use case inputs
3. **External Service Adapters**: Integrate with third-party services

### 7. Configure Dependency Injection

Wire everything together in NestJS modules:

1. Register use cases as providers
2. Provide repository implementations using interface tokens
3. Import required infrastructure modules (TypeORM, etc.)

### 8. Apply Best Practices

Follow these principles throughout implementation:

1. **Dependency Rule**: Dependencies only point inward. Domain knows nothing about NestJS, TypeORM, or HTTP.
2. **Rich Domain Models**: Put business logic in entities, not services. Avoid anemic domain models.
3. **Immutability**: Value objects must be immutable. Create new instances instead of modifying.
4. **Interface Segregation**: Keep repository interfaces small and focused.
5. **Constructor Injection**: Use NestJS DI in outer layers only. Domain entities use plain constructors.
6. **Validation**: Validate at boundaries (DTOs) and enforce invariants in domain.
7. **Testing**: Domain layer tests require no NestJS testing module - pure unit tests.
8. **Transactions**: Keep transactions in the application layer, not domain.

## Examples

For detailed code examples covering all aspects of Clean Architecture implementation, see:

- **[references/examples.md](references/examples.md)** - Complete examples including:
  - Value Objects (Email, Money)
  - Entities with Business Logic (OrderItem)
  - Aggregate Roots with Domain Events (Order)
  - Repository Ports (Interfaces)
  - Use Cases (Application Layer)
  - Repository Adapters (Infrastructure)
  - Controller Adapters (HTTP)
  - Module Configuration (DI setup)

## Best Practices

For comprehensive guidance on Clean Architecture best practices, including:

- **Core Principles**: Dependency Rule, Rich Domain Models, Immutability, Interface Segregation
- **Testing Strategies**: Unit testing domain, integration testing application, E2E testing adapters
- **Performance Considerations**: Aggregate design, caching strategy, lazy loading

See **[references/best-practices.md](references/best-practices.md)**

## Constraints and Warnings

Important constraints, common pitfalls, and implementation warnings:

- **Architecture Constraints**: Dependency rule violations, domain purity requirements, interface location rules
- **Common Pitfalls**: Leaky abstractions, anemic domain models, wrong layer dependencies, missing ports
- **Implementation Warnings**: Mapping overhead, learning curve, boilerplate code, transaction boundaries
- **Performance Considerations**: Aggregate size, database queries, caching strategies

See **[references/constraints.md](references/constraints.md)**

## Quick Start

1. Read the architectural layers overview above
2. Review the [examples.md](references/examples.md) for implementation patterns
3. Study [best-practices.md](references/best-practices.md) for core principles
4. Check [constraints.md](references/constraints.md) to avoid common pitfalls
5. Start implementing your domain layer with pure TypeScript classes
6. Add application layer use cases to orchestrate business logic
7. Implement adapters for infrastructure concerns
8. Configure dependency injection in NestJS modules

## References

- `references/examples.md` - Complete code examples for all layers
- `references/best-practices.md` - Comprehensive best practices and principles
- `references/constraints.md` - Constraints, pitfalls, and warnings

© Giuseppe Trisciuoglio · MIT · giuseppe-trisciuoglio/developer-kit

Похожие скиллы

Все скиллы по теме «Бэкенд и API» →

Сначала — clean-architecture от других авторов.

clean-architecture wondelai Скилл clean-architecture держит бизнес-правила отдельно от фреймворка и базы: исходники зависят только от внутренних слоёв, и это проверяется по чек-листу. CX Codex +1 8 000установок clean-architecture codewithmukesh Скилл clean-architecture для .NET-проектов: раскладывает код по четырём слоям, следит за направлением зависимостей и подсказывает, где живут use case-хендлеры. CX Codex +1 4 200установок clean-architecture ciembor Скилл clean-architecture для Claude Code применяет правила чистой архитектуры к решениям о границах между бизнес-логикой и техническими деталями. Агент подключает его при работе с зависимостями, сценариями использования и слоями приложения. CX Codex +1 645установок clean-architecture giuseppe-trisciuoglio Проектирование многоуровневых Java 21+ приложений на Spring Boot 3.5+. Отделяет бизнес-логику от фреймворка через Clean Architecture, Hexagonal Architecture и Domain-Driven Design. CX Codex +1 4 200установок clean-architecture pproenca Скилл clean-architecture с 42 правилами из книги Роберта Мартина: подсказывает агенту, куда направлять зависимости и где проводить границы слоёв. CX Codex +1 2 100установок nestjs-modular-monolith Felipe Rodrigues - github.com/felipfr Скилл nestjs-modular-monolith ведёт от анализа домена до кода: границы модулей, DDD, Clean Architecture и CQRS в одном бэкенде на NestJS. CX Codex +1 353установок go-backend-clean-architecture rebyteai-template Скилл go-backend-clean-architecture разворачивает в проекте шаблон Go-бэкенда на Gin с MongoDB, JWT-авторизацией и слоями Clean Architecture — от клонирования до запуска. CX Codex +1 105установок android-clean-architecture affaan-m Скилл android-clean-architecture подсказывает агенту, как раскладывать Android- и KMP-проект по слоям: модули, зависимости, UseCase, репозитории, работа с Room, SQLDelight и Ktor. CX Codex +1 7 200установок architecture-patterns Seth Hobson Скилл architecture-patterns помогает спроектировать слои backend-сервиса и разделить бизнес-логику с инфраструктурой. Пригодится при создании микросервиса, рефакторинге монолита и поиске циклических зависимостей. CX Codex +1 24 144установок architecture-advisor codewithmukesh Скилл architecture-advisor задаёт вопросы про домен, команду и срок жизни системы, а потом советует архитектуру для .NET-проекта. Пригодится до того, как разложить решение по папкам. CX Codex +1 4 000установок V3 Core Implementation ruvnet Скилл V3 Core Implementation для Claude Code и Codex. Собирает каркас ядра claude-flow v3 на TypeScript и раздаёт домены субагенту core-implementer. Проект уже размечен по DDD. CX Codex +1 1 100установок

Из того же набора191

Весь набор →
nestjs-database-expert Субагент nestjs-database-expert для Claude Code помогает проектировать базы данных в NestJS: настраивает Drizzle ORM, генерирует миграции и пишет типизированные запросы. CX Codex ★ 372звёзд репо devkit.verify-skill Команда devkit.verify-skill проверяет скилл по требованиям DevKit, структуре шаблона и зависимостям. Запустите команду перед публикацией или после изменений. CX Codex +1 ★ 372звёзд репо aws-cloudformation-dynamodb Скилл aws-cloudformation-dynamodb для Claude Code даёт шаблоны CloudFormation для таблиц DynamoDB: ключи, индексы, режимы ёмкости, TTL и стримы. Описывает инфраструктуру кодом. CX Codex +1 ★ 372звёзд репо devkit.java.write-unit-tests Команда devkit.java.write-unit-tests создаёт модульные тесты на JUnit 5, Mockito и AssertJ по пути к Java-классу. Пригодится при тестировании сервисов, контроллеров и утилит в Spring Boot. CX Codex +1 ★ 372звёзд репо spring-boot-backend-development-expert Субагент spring-boot-backend-development-expert для Claude по бэкенду на Spring Boot: реализует фичи, раскладывает код по Clean Architecture и пишет тесты к тому, что сделал. CX Codex ★ 372звёзд репо java-security-expert Субагент java-security-expert проводит аудит безопасности Java и Spring Boot: находит уязвимости по OWASP Top 10, проверяет OAuth2 и настраивает DevSecOps-пайплайны. CX Codex ★ 372звёзд репо general-code-reviewer Субагент general-code-reviewer проверяет изменения на ошибки, уязвимости и проблемы качества, а в отчёт включает только находки с уверенностью не ниже 80%. CX Codex ★ 372звёзд репо aws-cloudformation-vpc Скилл aws-cloudformation-vpc для Claude Code содержит шаблоны CloudFormation для VPC и помогает создавать сетевую инфраструктуру AWS. CX Codex +1 ★ 372звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой