Skip to main content

Posts

Showing posts with the label Hexagonal Architecture

Hexagonal Architecture in NestJS: Decoupling TypeORM from Domain Entities

  The Coupling Trap The default NestJS + TypeORM pattern leads to a deceptive trap. You start by defining a User class, decorate it with  @Entity() , add a few  @Column()  decorators, and then write methods like  isSubscriptionActive()  directly on that class. It looks efficient until you try to unit test your business logic. Suddenly, you cannot instantiate a  User  without dragging in TypeORM's metadata storage. Your domain logic is now tightly coupled to your persistence infrastructure. If you change your database from SQL to Mongo, or just rename a column, you risk breaking business rules that shouldn't care about storage details. This is the "Active Record" anti-pattern in complex systems: it conflates  what the data is  (Domain) with  how the data is stored  (Infrastructure). The Root Cause: Mixing Concerns Under the hood, TypeORM decorators modify the class prototype to register metadata. When you inject a TypeORM reposi...

Hexagonal Architecture Anti-Patterns: Leaking Persistence Models into the Domain

  We treat Hexagonal Architecture (Ports and Adapters) as the gold standard for decoupling business logic from infrastructure. Ideally, the core domain doesn't know whether data is stored in PostgreSQL, Mongo, or an in-memory map. However, the most common anti-pattern I see in code reviews—across both Spring Boot and NestJS ecosystems—is the  Leaky Persistence Model . This happens when the class annotated with  @Entity  (JPA) or  @Entity()  (TypeORM) is passed directly into the core domain use cases. If your "Domain Model" has database annotations on it, you have broken the architecture. You are no longer writing Hexagonal Architecture; you are writing a monolith coupled to your ORM. The Root Cause: Why We Do It Two drivers cause this anti-pattern: Boilerplate Aversion:  Creating a  User  domain class  and  a  UserEntity  database class feels like redundant work. They often share 90% of the same fields. Misunderstanding OR...