Pular para o conteúdo
  1. Padrões
  2. Arquitetura

hexagonal

Isola o domínio no centro e conecta o mundo externo por portas e adaptadores.
Status
Em breve
Categoria
Arquitetura
Implementação em Arquiteturapattern/architecture/hexagonalintermediário4 passos≈ 3 min

Órbita

  1. Código
  2. Arquitetura
  3. Dados
  4. Integração
  5. Resiliência

Quando usar

Domínio rico que precisa trocar infraestrutura sem reescrita

Adaptador condutor HTTPPorta de entradaInterfaceTransferUseCaseNúcleo: saldo e contasPorta de saídaInterfaceAccountRepositoryAdaptador conduzidoPostgreSQLimplementa

Como funciona

  1. 1

    Portas só com tipos do domínio

  2. 2

    O núcleo recebe a porta por injeção; recusa é resultado, não exceção

  3. 3

    Adaptador PostgreSQL trava com FOR UPDATE em ordem de id

  4. 4

    Adaptador HTTP traduz recusa em status; a raiz de composição liga tudo

Nível
intermediário
Infraestrutura
B — um serviço (docker.sh)
Domínio financeiro
Conta correnteSaldo
Abrir a implementação completa

README.mdpattern/architecture/hexagonal

thiagoeti/pattern/hexagonal

O domínio define as portas na língua do negócio; HTTP e PostgreSQL são adaptadores plugados, trocáveis sem tocar na regra.

Cenário

Transferência entre contas pelo app: o núcleo exige contas existentes e saldo; HTTP e PostgreSQL ficam fora.

Como funciona

  1. Portas só com tipos do domínio
  2. O núcleo recebe a porta por injeção; recusa é resultado, não exceção
  3. Adaptador PostgreSQL trava com FOR UPDATE em ordem de id
  4. Adaptador HTTP traduz recusa em status; a raiz de composição liga tudo

Código

src/demo.ts

// Demo: the transfer core talks only to ports; an HTTP adapter drives it and a PostgreSQL adapter is driven by it.
import { Elysia, t } from "elysia";
import pg from "pg";

// Ports, in the language of the domain. Driving: what the outside calls. Driven: what the core needs, never how.
type InputTransfer = { sourceAccountId: string; destinationAccountId: string; amountCents: number };
type OutputTransfer = { status: "completed"; sourceBalanceCents: number } | { status: "refused"; reason: string };
interface InterfaceTransferUseCase {
  execute(input: InputTransfer): Promise<OutputTransfer>;
}
interface InterfaceAccountRepository {
  // Both accounts held until the work ends; everything inside commits together or not at all.
  accountsLock<T>(ids: string[], work: (balances: Map<string, number>, balanceSave: (id: string, cents: number) => Promise<void>) => Promise<T>): Promise<T>;
}

// Core: the transfer rule. Imports nothing technical — testable with a fake repository.
const useCaseTransferCreate = (repository: InterfaceAccountRepository): InterfaceTransferUseCase => ({
  execute: (input) =>
    repository.accountsLock([input.sourceAccountId, input.destinationAccountId], async (balances, balanceSave) => {
      const source = balances.get(input.sourceAccountId);
      const destination = balances.get(input.destinationAccountId);
      if (source === undefined || destination === undefined) return { status: "refused", reason: "account.not-found" };
      if (source < input.amountCents) return { status: "refused", reason: "balance.insufficient" };
      await balanceSave(input.sourceAccountId, source - input.amountCents);
      await balanceSave(input.destinationAccountId, destination + input.amountCents);
      return { status: "completed", sourceBalanceCents: source - input.amountCents };
    }),
});

// Driven adapter: satisfies the repository port with PostgreSQL; SQL and rows stop here.
const repositoryPostgresCreate = (pool: pg.Pool): InterfaceAccountRepository => ({
  async accountsLock(ids, work) {
    const client = await pool.connect();
    try {
      await client.query("BEGIN");
      const { rows } = await client.query<{ id: string; balance_cents: string }>("SELECT id, balance_cents FROM accounts WHERE id = ANY(## Executar) ORDER BY id FOR UPDATE", [ids]);
      const result = await work(new Map(rows.map((row) => [row.id, Number(row.balance_cents)])), async (id, cents) => void (await client.query("UPDATE accounts SET balance_cents = $2 WHERE id = ## Executar", [id, cents])));
      await client.query("COMMIT");
      return result;
    } catch (error) {
      await client.query("ROLLBACK");
      throw error;
    } finally {
      client.release();
    }
  },
});

// Driving adapter: HTTP → input port → response; a refusal reason becomes a status code, no rule here.
const controllerTransfer = (useCase: InterfaceTransferUseCase) =>
  new Elysia().post("/transfers", async ({ body, status }) => {
    const output = await useCase.execute(body);
    return output.status === "completed" ? status(201, output) : status(422, output);
  }, { body: t.Object({ sourceAccountId: t.String(), destinationAccountId: t.String(), amountCents: t.Integer({ minimum: 1 }) }) });

// Composition root: the only place that knows every technology and plugs the adapters into the core.
const pool = new pg.Pool({ connectionString: Bun.env.HEXAGONAL_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/hexagonal_db" });
const app = controllerTransfer(useCaseTransferCreate(repositoryPostgresCreate(pool)));

const suffix = Date.now().toString(36).toUpperCase();
await pool.query("INSERT INTO accounts (id, holder_name, balance_cents) VALUES (## Executar, 'Alice Ferreira', 2200000), ($2, 'Bruno Martins', 900000)", [`CC-A-${suffix}`, `CC-B-${suffix}`]);
const response = await app.handle(new Request("http://localhost/transfers", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ sourceAccountId: `CC-A-${suffix}`, destinationAccountId: `CC-B-${suffix}`, amountCents: 500_000 }) }));
console.log(`  [HTTP] R$ 5000.00 Alice → Bruno → ${response.status} ${await response.text()}`);
await pool.end();

Executar

./docker.sh
until docker exec hexagonal-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; done
bun install
bun run demo
docker rm -f hexagonal-db

Saída: 201 com status completed e sourceBalanceCents 1700000.

Trade-offs

Vantagem Desvantagem
Núcleo testável sem banco Mais indireções
Nova entrada reaproveita o núcleo Porta mal desenhada vira CRUD
Esc

↑ ↓ navegarEnter abrir239 resultados