MCPcopy
hub / github.com/Sairyss/domain-driven-hexagon

github.com/Sairyss/domain-driven-hexagon @main sqlite

repository ↗ · DeepWiki ↗
298 symbols 551 edges 97 files 17 documented · 6%
README

Domain-Driven Hexagon

Check out my other repositories:

  • Backend best practices - Best practices, tools and guidelines for backend development.
  • System Design Patterns - list of topics and resources related to distributed systems, system design, microservices, scalability and performance, etc.
  • Full Stack starter template - template for full stack applications based on TypeScript, React, Vite, ChakraUI, tRPC, Fastify, Prisma, zod, etc.

The main emphasis of this project is to provide recommendations on how to design software applications. This readme includes techniques, tools, best practices, architectural patterns and guidelines gathered from different sources.

Code examples are written using NodeJS, TypeScript, NestJS framework and Slonik for the database access.

Patterns and principles presented here are framework/language agnostic. Therefore, the above technologies can be easily replaced with any alternative. No matter what language or framework is used, any application can benefit from principles described below.

Note: code examples are adapted to TypeScript and frameworks mentioned above.

(Implementations in other languages will look differently)

Everything below is provided as a recommendation, not a rule. Different projects have different requirements, so any pattern mentioned in this readme should be adjusted to project needs or even skipped entirely if it doesn't fit. In real world production applications, you will most likely only need a fraction of those patterns depending on your use cases. More info in this section.


Architecture

This is an attempt to combine multiple architectural patterns and styles together, such as:

And many others (more links below in every chapter).

Before we begin, here are the PROS and CONS of using a complete architecture like this:

Pros

  • Independent of external frameworks, technologies, databases, etc. Frameworks and external resources can be plugged/unplugged with much less effort.
  • Easily testable and scalable.
  • More secure. Some security principles are baked in design itself.
  • The solution can be worked on and maintained by different teams, without stepping on each other's toes.
  • Easier to add new features. As the system grows over time, the difficulty in adding new features remains constant and relatively small.
  • If the solution is properly broken apart along bounded context lines, it becomes easy to convert pieces of it into microservices if needed.

Cons

  • This is a sophisticated architecture which requires a firm understanding of quality software principles, such as SOLID, Clean/Hexagonal Architecture, Domain-Driven Design, etc. Any team implementing such a solution will almost certainly require an expert to drive the solution and keep it from evolving the wrong way and accumulating technical debt.

  • Some practices presented here are not recommended for small-medium sized applications with not a lot of business logic. There is added up-front complexity to support all those building blocks and layers, boilerplate code, abstractions, data mapping etc. Thus, implementing a complete architecture like this is generally ill-suited to simple CRUD applications and could over-complicate such solutions. Some principles which are described below can be used in smaller sized applications, but must be implemented only after analyzing and understanding all pros and cons.

Diagram

Domain-Driven Hexagon Diagram is mostly based on this one + others found online

In short, data flow looks like this (from left to right):

  • Request/CLI command/event is sent to the controller using plain DTO;
  • Controller parses this DTO, maps it to a Command/Query object format and passes it to an Application service;
  • Application service handles this Command/Query; it executes business logic using domain services and entities/aggregates and uses the infrastructure layer through ports(interfaces);
  • Infrastructure layer maps data to a format that it needs, retrieves/persists data from/to a database, uses adapters for other I/O communications (like sending an event to an external broker or calling external APIs), maps data back to domain format and returns it back to Application service;
  • After the Application service finishes doing its job, it returns data/confirmation back to Controllers;
  • Controllers return data back to the user (if application has presenters/views, those are returned instead).

Each layer is in charge of its own logic and has building blocks that usually should follow a Single-responsibility principle when possible and when it makes sense (for example, using Repositories only for database access, using Entities for business logic, etc.).

Keep in mind that different projects can have more or less steps/layers/building blocks than described here. Add more if the application requires it, and skip some if the application is not that complex and doesn't need all that abstraction.

General recommendation for any project: analyze how big/complex the application will be, find a compromise and use as many layers/building blocks as needed for the project and skip ones that may over-complicate things.

More in details on each step below.

Modules

This project's code examples use separation by modules (also called components). Each module's name should reflect an important concept from the Domain and have its own folder with a dedicated codebase. Each business use case inside that module gets its own folder to store most of the things it needs (this is also called Vertical Slicing). It's easier to work on things that change together if those things are gathered relatively close to each other. Think of a module as a "box" that groups together related business logic.

Using modules is a great way to encapsulate parts of highly cohesive business domain rules.

Try to make every module independent and keep interactions between modules minimal. Think of each module as a mini application bounded by a single context. Consider module internals private and try to avoid direct imports between modules (like importing a class import SomeClass from '../SomeOtherModule') since this creates tight coupling and can turn your code into a spaghetti and application into a big ball of mud.

Few advices to avoid coupling:

  • Try not to create dependencies between modules or use cases. Instead, move shared logic into a separate files and make both depend on that instead of depending on each other.
  • Modules can cooperate through a mediator or a public facade, hiding all private internals of the module to avoid its misuse, and giving public access only to certain pieces of functionality that meant to be public.
  • Alternatively modules can communicate with each other by using messages. For example, you can send commands using a commands bus or subscribe to events that other modules emit (more info on events and commands bus below).

This ensures loose coupling, refactoring of a module internals can be done easier because outside world only depends on module's public interface, and if bounded contexts are defined and designed properly each module can be easily separated into a microservice if needed without touching any domain logic or major refactoring.

Keep your modules small. You should be able to rewrite a module in a relatively short period of time. This applies not only to modules pattern, but to software development in general: objects, functions, microservices, processes, etc. Keep them small and composable. This is incredibly powerful in a constantly changing environments of software development, since when your requirements change, changing small modules is much easier than changing a big program. You can just delete a module and rewrite it from scratch in a matter of days. This idea is further described in this talk: Greg Young - The art of destroying software.

Code Examples:

  • Check src/modules directory structure.
  • src/modules/user/commands - "commands" directory in a user module includes business use cases (commands) that a module can execute, each with its own Vertical Slice.

Read more:

Each module consists of layers described below.

Application Core

This is the core of the system which is built using DDD building blocks:

Domain layer:

  • Entities
  • Aggregates
  • Domain Services
  • Value Objects
  • Domain Errors

Application layer:

  • Application Services
  • Commands and Queries
  • Ports

Note: different implementations may have slightly different layer structures depending on applications needs. Also, more layers and building blocks may be added if needed.


Application layer

Application Services

Application Services (also called "Workflow Services", "Use Cases", "Interactors", etc.) are used to orchestrate the steps required to fulfill the commands imposed by the client.

Application services:

  • Typically used to orchestrate how the outside world interacts with your application and performs tasks required by the end users;
  • Contain no domain-specific business logic;
  • Operate on scalar types, transforming them into Domain types. A scalar type can be considered any type that's unknown to

Extension points exported contracts — how you extend this code

UserRepositoryPort (Interface)
(no doc) [2 implementers]
src/modules/user/database/user.repository.port.ts
Mapper (Interface)
(no doc) [2 implementers]
src/libs/ddd/mapper.interface.ts
CreateWalletProps (Interface)
(no doc)
src/modules/wallet/domain/wallet.entity.ts
ObjectLiteral (Interface)
(no doc)
src/libs/types/object-literal.type.ts
WalletProps (Interface)
(no doc)
src/modules/wallet/domain/wallet.entity.ts
LoggerPort (Interface)
(no doc)
src/libs/ports/logger.port.ts
FindUsersParams (Interface)
(no doc)
src/modules/user/database/user.repository.port.ts
SerializedException (Interface)
(no doc)
src/libs/exceptions/exception.base.ts

Core symbols most depended-on inside this repo

getRequestId
called by 11
src/libs/application/context/AppRequestContext.ts
debug
called by 8
src/libs/ports/logger.port.ts
getContext
called by 8
src/libs/application/context/AppRequestContext.ts
isEmpty
called by 6
src/libs/guard.ts
log
called by 6
src/libs/ports/logger.port.ts
execute
called by 4
src/modules/user/commands/create-user/create-user.service.ts
validate
called by 4
src/modules/user/domain/user.entity.ts
lengthIsBetween
called by 3
src/libs/guard.ts

Shape

Class 129
Method 97
Function 53
Interface 18
Enum 1

Languages

TypeScript100%

Modules by API surface

src/libs/exceptions/exceptions.ts14 symbols
src/libs/ddd/entity.base.ts13 symbols
src/libs/db/sql-repository.base.ts11 symbols
src/modules/user/domain/user.entity.ts10 symbols
src/libs/ddd/repository.port.ts10 symbols
src/libs/application/context/AppRequestContext.ts10 symbols
tests/setup/jestSetupAfterEnv.ts8 symbols
src/modules/wallet/domain/wallet.entity.ts8 symbols
src/libs/ddd/value-object.base.ts8 symbols
src/modules/user/queries/find-users/find-users.query-handler.ts7 symbols
src/modules/user/domain/value-objects/address.value-object.ts7 symbols
src/modules/user/commands/delete-user/delete-user.service.ts7 symbols

Dependencies from manifests, versioned

@nestjs/apollo10.1.3 · 1×
@nestjs/cli9.0.0 · 1×
@nestjs/common9.0.0 · 1×
@nestjs/core9.0.0 · 1×
@nestjs/cqrs9.0.1 · 1×
@nestjs/event-emitter1.3.1 · 1×
@nestjs/graphql10.1.2 · 1×
@nestjs/microservices9.1.2 · 1×
@nestjs/platform-express9.0.0 · 1×
@nestjs/schematics9.0.0 · 1×
@nestjs/swagger6.1.2 · 1×
@nestjs/testing9.0.0 · 1×

For agents

$ claude mcp add domain-driven-hexagon \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact