pattern/architecture/onion
- Bun
- ElysiaJS
- PostgreSQL
- TypeScript
- node-postgres
- Docker
Domínio no centro, envolto por serviços de domínio, aplicação e infraestrutura; toda dependência aponta para dentro.
pattern/architecture/onion
Cenário
Transferência de R$ 6.000,00 sujeita a saldo: regra no centro, PostgreSQL e HTTP no anel externo.
Planta
FluxoComo funciona
4passos
Domínio no centro, envolto por serviços de domínio, aplicação e infraestrutura
Esconde cada passo: lembre antes de tocar para revelar.
Account e funções puras validam e aplicam sem mutar
O serviço de domínio declara o gateway por intenção (accountsLock, transferRecord)
O serviço de aplicação abre a unidade de trabalho e devolve DTO
A infraestrutura implementa o gateway no PostgreSQL e traduz em HTTP
Trade-offs
O que se ganha, o que se paga
Vantagens
Regra testável sem banco nem HTTP
Troca de banco não toca os anéis internos
Custos
Mais indireções que CRUD
Mapeamento em cada fronteira
Código
pattern/architecture/onion
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec onion-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 onion-dbSaída: 201 com status completed e sourceBalanceCents 1900000.
Código
src/demo.ts// Demo: a transfer enters at the infrastructure ring and reaches the domain model at the center; every dependency points inward.
import { Elysia, t } from "elysia";
import pg from "pg";
// Ring 1 — domain model: the account and its rule as a plain type and pure functions. Imports nothing.
type Account = { readonly id: string; readonly balanceCents: number };
const transferValidate = (source: Account, amountCents: number) => (source.balanceCents < amountCents ? `available R$ ${(source.balanceCents / 100).toFixed(2)}` : null);
const transferApply = (source: Account, destination: Account, amountCents: number) => ({
source: { ...source, balanceCents: source.balanceCents - amountCents },
destination: { ...destination, balanceCents: destination.balanceCents + amountCents },
});
// Ring 2 — domain services: an operation over two entities, and the gateway it needs, declared by intention, not CRUD.
interface InterfaceAccountGateway {
accountsLock(ids: string[]): Promise<Map<string, Account>>;
transferRecord(source: Account, destination: Account, amountCents: number): Promise<void>;
}
async function fundsTransfer(gateway: InterfaceAccountGateway, sourceId: string, destinationId: string, amountCents: number): Promise<string | Account> {
const accounts = await gateway.accountsLock([sourceId, destinationId]);
const refusal = transferValidate(accounts.get(sourceId)!, amountCents);
if (refusal) return refusal;
const applied = transferApply(accounts.get(sourceId)!, accounts.get(destinationId)!, amountCents);
await gateway.transferRecord(applied.source, applied.destination, amountCents);
return applied.source;
}
// Ring 3 — application services: one use case per operation; opens the unit of work, returns a DTO.
type UnitOfWork = <T>(work: (gateway: InterfaceAccountGateway) => Promise<T>) => Promise<T>;
const useCaseFundsTransfer = (unitOfWork: UnitOfWork) => (input: { sourceAccountId: string; destinationAccountId: string; amountCents: number }) =>
unitOfWork(async (gateway) => {
const result = await fundsTransfer(gateway, input.sourceAccountId, input.destinationAccountId, input.amountCents);
return typeof result === "string" ? { status: "refused", detail: result } : { status: "completed", sourceBalanceCents: result.balanceCents };
});
// Ring 4 — infrastructure: the PostgreSQL gateway and the HTTP controller; rows and status codes stop here.
const pool = new pg.Pool({ connectionString: Bun.env.ONION_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/onion_db" });
const unitOfWorkPostgres: UnitOfWork = async (work) => {
const client = await pool.connect();
try {
await client.query("BEGIN");
const result = await work({
accountsLock: async (ids) => new Map((await client.query<{ id: string; balance_cents: string }>("SELECT id, balance_cents FROM accounts WHERE id = ANY($1) ORDER BY id FOR UPDATE", [ids])).rows.map((row) => [row.id, { id: row.id, balanceCents: Number(row.balance_cents) }])),
transferRecord: async (source, destination, amountCents) => {
for (const account of [source, destination]) await client.query("UPDATE accounts SET balance_cents = $2 WHERE id = $1", [account.id, account.balanceCents]);
await client.query("INSERT INTO transfers (source_account_id, destination_account_id, amount_cents) VALUES ($1, $2, $3)", [source.id, destination.id, amountCents]);
},
});
await client.query("COMMIT");
return result;
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
};
const transfer = useCaseFundsTransfer(unitOfWorkPostgres);
const app = new Elysia().post("/transfers", async ({ body, status }) => {
const output = await transfer(body);
return status(output.status === "completed" ? 201 : 422, output);
}, { body: t.Object({ sourceAccountId: t.String(), destinationAccountId: t.String(), amountCents: t.Integer({ minimum: 1 }) }) });
const suffix = Date.now().toString(36).toUpperCase();
await pool.query("INSERT INTO accounts (id, holder_name, balance_cents) VALUES ($1, 'Alice Ferreira', 2500000), ($2, 'Bruno Martins', 700000)", [`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: 600_000 }) }));
console.log(` [HTTP] R$ 6000.00 Alice → Bruno → ${response.status} ${await response.text()}`);
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
Parecidos
Por que se relacionam
Teste rápido
Qual destes combina com Arquitetura Onion?
Modelo de domínio no núcleo. Abrir Domain-Driven Design
Seu progresso
0/157 estudados
Fica salvo só neste navegador.