pattern/enterprise/data-access-styles
- Bun
- PostgreSQL
- TypeScript
- node-postgres
- Docker
Dois estilos de Fowler para ligar objeto e banco: Active Record se salva sozinho; Data Mapper traduz entre domínio puro e tabela.
pattern/enterprise/data-access-styles
Cenário
Favorecido PIX (cadastro puro) usa Active Record; conta corrente (regra de saldo) usa Data Mapper.
Planta
Fluxo3 passos — reproduza para seguir o fluxo
Como funciona
4passos
Active Record, que se salva sozinho, contra Data Mapper, que traduz entre domínio puro e tabela
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
Beneficiary tem o próprio SQL: create e save
Account só tem a regra (withdraw), sem banco
mapperAccount carrega com FOR UPDATE, reconstrói e grava o saldo
Um estilo por agregado
Trade-offs
O que se ganha, o que se paga
Vantagens
Active Record: uma classe só, pouco código para cadastro simples
Data Mapper: domínio puro, regra testada sem banco
Custos
Active Record: regra presa ao SQL, teste exige banco
Data Mapper: domínio e mapper, mais código por agregado
Código
pattern/enterprise/data-access-styles
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec data-access-styles-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 data-access-styles-dbSaída: o favorecido landlord@bank.com se grava como “Aluguel apartamento”; a conta de João saca R$ 400,00 pelo mapper e fica com R$ 1.100,00.
Código
src/demo.ts// Demo: a PIX beneficiary saves itself (Active Record); an account with balance rules is persisted by a separate mapper (Data Mapper).
import pg from "pg";
const pool = new pg.Pool({ connectionString: Bun.env.DATA_ACCESS_STYLES_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/data_access_styles_db" });
// Active Record: model and table gateway are the same class; changes stay in memory until save().
class Beneficiary {
private constructor(readonly id: string, public nickname: string, readonly pixKey: string) {}
static async create(nickname: string, pixKey: string): Promise<Beneficiary> {
// Upsert by PIX key, so a second run finds the same beneficiary instead of failing on UNIQUE.
const { rows } = await pool.query<{ id: string }>(
"INSERT INTO beneficiaries (nickname, pix_key, bank_code) VALUES ($1, $2, '260') ON CONFLICT (pix_key) DO UPDATE SET nickname = EXCLUDED.nickname RETURNING id",
[nickname, pixKey],
);
return new Beneficiary(rows[0]!.id, nickname, pixKey);
}
async save(): Promise<void> {
await pool.query("UPDATE beneficiaries SET nickname = $2, updated_at = now() WHERE id = $1", [this.id, this.nickname]);
}
}
// Data Mapper domain: the banking rule, with no import from the database — testable without one.
class Account {
constructor(readonly id: string, public balanceCents: number) {}
withdraw(amountCents: number): void {
if (amountCents > this.balanceCents) throw new Error(`balance ${this.balanceCents} cents, asked ${amountCents}`);
this.balanceCents -= amountCents;
}
}
// Only the mapper knows the SQL: it rebuilds the object from the row and writes its state back.
const mapperAccount = {
async idFind(client: pg.PoolClient, id: string): Promise<Account> {
const { rows } = await client.query<{ id: string; balance_cents: string }>("SELECT id, balance_cents FROM accounts WHERE id = $1 FOR UPDATE", [id]);
const row = rows[0]!;
return new Account(row.id, Number(row.balance_cents));
},
async update(client: pg.PoolClient, account: Account): Promise<void> {
await client.query("UPDATE accounts SET balance_cents = $2, updated_at = now() WHERE id = $1", [account.id, account.balanceCents]);
},
};
const beneficiary = await Beneficiary.create("Aluguel", "landlord@bank.com");
beneficiary.nickname = "Aluguel apartamento";
await beneficiary.save();
console.log(` [ACTIVE RECORD] beneficiary ${beneficiary.pixKey} saved itself as "${beneficiary.nickname}"`);
const { rows: [created] } = await pool.query<{ id: string }>("INSERT INTO accounts (owner_name, balance_cents) VALUES ('Joao Silva', 150000) RETURNING id");
const client = await pool.connect();
try {
await client.query("BEGIN");
const account = await mapperAccount.idFind(client, created!.id);
account.withdraw(40_000);
await mapperAccount.update(client, account);
await client.query("COMMIT");
console.log(` [DATA MAPPER] Joao Silva account withdrew R$ 400.00, balance R$ ${(account.balanceCents / 100).toFixed(2)}`);
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
await pool.end();
Nível
intermediário
5/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
Trilhapasso 2 de 6
Lógica de domínio (PoEAA)
Relações
Onde ele se encaixa
Por que se relacionam
Combina com
Teste rápido
Qual destes combina com Data Access Styles: Active Record vs. Data Mapper?
O mapper usa o pool de conexões. Abrir Connection Pool
Seu progresso
0/157 estudados
Fica salvo só neste navegador.