Pular para o conteúdo

Domain-Driven Design (DDD)

DDD tático põe a regra no modelo: Money (Value Object em centavos), Account (Aggregate Root que protege o saldo e registra Domain Events). Use no subdomínio core.

passos
4
arquivos
7
testes
0
tecnologias
5

Cenário

Alice transfere R$ 5.000,00; débito só com saldo, e account.money.debited gravado junto.

Planta

Sequência
4/4
BEGIN, SELECT conta FOR UPDATE1debit(Money, transferId)2invariante ok, evento account.money.debited3UPDATE accounts + INSERT account_events, COMMIT4Serviço de aplicaçãoPostgreSQLAccount
4

4 passos — reproduza para seguir o fluxo

Como funciona

4passos

DDD tático com Value Object, Aggregate Root e Domain Events protegendo a regra no modelo

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    Money aceita só centavos inteiros não negativos, imutável

  2. 2

    Account.debit checa o saldo e registra o evento

  3. 3

    Um aggregate por transação

  4. 4

    Aggregate e eventos na mesma transação; UNIQUE (transfer_id, type) barra repetição

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Nenhum chamador viola o saldo

  • Fato gravado com o dado

Custos

  • Mais tipos que um CRUD

  • Conversão entre linha e aggregate

Código

pattern/architecture/ddd

7 arquivos

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

sql/

  • 01_schema.sqlschema

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec ddd-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f ddd-db

Saída: débito de R$ 5000.00 deixa saldo de R$ 15000.00; um evento account.money.debited gravado com {"amountCents":500000}.

Requisitos
BunDocker
Sobe junto
PostgreSQL

Código

src/demo.ts

// Demo: tactical DDD — Money value object, Account aggregate root guarding its balance, and a domain event saved with the change.
import pg from "pg";

// Value object: whole cents and currency, immutable, valid from the moment it exists; equality by value.
class Money {
  private constructor(readonly cents: number, readonly currency: "BRL") {}

  static of(cents: number): Money {
    if (!Number.isSafeInteger(cents) || cents < 0) throw new Error(`amount must be whole non-negative cents: ${cents}`);
    return new Money(cents, "BRL");
  }

  subtract(other: Money): Money {
    return Money.of(this.cents - other.cents);
  }

  isGreaterThan(other: Money): boolean {
    return this.cents > other.cents;
  }

  toString(): string {
    return `R$ ${(this.cents / 100).toFixed(2)}`;
  }
}

type EventMoneyDebited = { type: "account.money.debited"; accountId: string; transferId: string; amount: Money };

// Aggregate root: the balance changes only through it; guards first, state after; every change records a domain event.
class Account {
  private events: EventMoneyDebited[] = [];

  constructor(readonly id: string, private balance: Money) {}

  debit(amount: Money, transferId: string): void {
    if (amount.isGreaterThan(this.balance)) throw new Error(`balance ${this.balance} below ${amount}`);
    this.balance = this.balance.subtract(amount);
    this.events.push({ type: "account.money.debited", accountId: this.id, transferId, amount });
  }

  balanceGet(): Money {
    return this.balance;
  }

  // Hands the recorded facts over exactly once.
  eventsPull(): EventMoneyDebited[] {
    const events = this.events;
    this.events = [];
    return events;
  }
}

const pool = new pg.Pool({ connectionString: Bun.env.DDD_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/ddd_db" });

// Application service: one transaction, one aggregate — load, call the domain, save the aggregate and its events together.
async function transferDebit(accountId: string, amountCents: number, transferId: string): Promise<Money> {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const { rows: [row] } = await client.query<{ id: string; balance_cents: string }>("SELECT id, balance_cents FROM accounts WHERE id = $1 FOR UPDATE", [accountId]);
    const account = new Account(row!.id, Money.of(Number(row!.balance_cents)));
    account.debit(Money.of(amountCents), transferId);
    await client.query("UPDATE accounts SET balance_cents = $2 WHERE id = $1", [account.id, account.balanceGet().cents]);
    for (const event of account.eventsPull()) {
      await client.query("INSERT INTO account_events (type, account_id, transfer_id, payload) VALUES ($1, $2, $3, $4)", [event.type, event.accountId, event.transferId, { amountCents: event.amount.cents }]);
    }
    await client.query("COMMIT");
    return account.balanceGet();
  } catch (error) {
    await client.query("ROLLBACK");
    throw error;
  } finally {
    client.release();
  }
}

const accountId = `CC-A-${Date.now().toString(36).toUpperCase()}`;
await pool.query("INSERT INTO accounts (id, holder_name, balance_cents) VALUES ($1, 'Alice Ferreira', 2000000)", [accountId]);
console.log(`  [ACCOUNT] debit of R$ 5000.00 → balance ${await transferDebit(accountId, 500_000, `TRF-${accountId}`)}`);
const { rows: events } = await pool.query<{ type: string; transfer_id: string; payload: { amountCents: number } }>("SELECT type, transfer_id, payload FROM account_events WHERE account_id = $1", [accountId]);
for (const event of events) console.log(`  [EVENT] ${event.type} ${event.transfer_id} ${JSON.stringify(event.payload)}`);
await pool.end();

Nível

intermediário

6/13

Linhas de TypeScript
67
Tipo
B — um serviço (docker.sh)

Domínio financeiro

  • Conta corrente
  • Saldo

Padrões do catálogo que implementa

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • accounts
  • account_events

Variáveis de ambiente

DDD_DATABASE_URL
postgres://postgres:postgres@localhost:5432/ddd_db
PostgreSQL behind the Account repository.
Esc

↑ ↓ navegarEnter abrir239 resultados