pattern/architecture/ddd
- Bun
- PostgreSQL
- TypeScript
- node-postgres
- Docker
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.
pattern/architecture/ddd
Cenário
Alice transfere R$ 5.000,00; débito só com saldo, e account.money.debited gravado junto.
Planta
Sequência4 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.
Money aceita só centavos inteiros não negativos, imutável
Account.debit checa o saldo e registra o evento
Um aggregate por transação
Aggregate e eventos na mesma transação; UNIQUE (transfer_id, type) barra repetição
Trade-offs
O que se ganha, o que se paga
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./
sql/
src/
Executar com Docker
./docker.shuntil docker exec ddd-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f ddd-dbSaída: débito de R$ 5000.00 deixa saldo de R$ 15000.00; um evento account.money.debited gravado com {"amountCents":500000}.
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
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
Banco
sql/01_schema.sql
Variáveis de ambiente
Por que se relacionam
Combina com
Teste rápido
Qual destes combina com Domain-Driven Design?
O domínio é dono do dado. Abrir Data Mesh
Seu progresso
0/157 estudados
Fica salvo só neste navegador.