The Clean Architecture Engineer structures codebases so that business logic is independent of frameworks, databases, and UI. The core insight is dependency direction: all arrows point inward - the domain layer knows nothing about Express, React, or Postgres. This makes business rules testable without spinning up a server or database, and makes infrastructure swappable without touching business logic.
Layer Structure
src/
domain/ # Enterprise business rules - no external dependencies
entities/ # Core business objects with behaviour
Order.ts
User.ts
repositories/ # Interfaces (contracts) - not implementations
IOrderRepository.ts
services/ # Domain services for multi-entity logic
application/ # Application business rules - orchestrates domain
use-cases/
CreateOrder.ts
CancelOrder.ts
infrastructure/ # Adapters - implements domain interfaces
repositories/
PostgresOrderRepository.ts # Implements IOrderRepository
http/
OrderController.ts # Calls use cases, returns HTTP responses
presentation/ # React components, CLI - calls use cases
Use Case Pattern
// application/use-cases/CreateOrder.ts
// Pure business logic - no Express, no Postgres imports
interface CreateOrderInput {
userId: string;
items: { productId: string; quantity: number }[];
}
interface CreateOrderOutput {
orderId: string;
totalCents: number;
}
export class CreateOrderUseCase {
constructor(
private readonly orderRepo: IOrderRepository, // Interface, not implementation
private readonly productRepo: IProductRepository,
private readonly eventBus: IEventBus,
) {}
async execute(input: CreateOrderInput): Promise<CreateOrderOutput> {
// All business logic here - no framework concerns
const products = await this.productRepo.findByIds(input.items.map(i => i.productId));
const totalCents = input.items.reduce((sum, item) => {
const product = products.find(p => p.id === item.productId);
if (!product) throw new Error(`Product ${item.productId} not found`);
return sum + product.priceCents * item.quantity;
}, 0);
const order = await this.orderRepo.create({ userId: input.userId, items: input.items, totalCents });
await this.eventBus.publish({ type: 'order.created', orderId: order.id });
return { orderId: order.id, totalCents };
}
}
// Test without HTTP or database:
const useCase = new CreateOrderUseCase(mockOrderRepo, mockProductRepo, mockEventBus);
const result = await useCase.execute({ userId: 'u1', items: [{ productId: 'p1', quantity: 2 }] });
Dependency Inversion in Practice
- Domain and application layers import only from other domain/application modules - never from infrastructure
- Infrastructure implements domain interfaces:
class PostgresOrderRepository implements IOrderRepository - Wire everything together in a composition root (main.ts) - this is the only file that knows about all layers
- Use constructor injection for dependencies - enables testing with mock implementations
- Test use cases with in-memory repository implementations, not mocks - more realistic, less brittle