Pular para o conteúdo

Arquitetura Onion (Cebola)

Domínio no centro, envolto por serviços de domínio, aplicação e infraestrutura; toda dependência aponta para dentro.

passos
4
arquivos
7
testes
0
tecnologias
6

Cenário

Transferência de R$ 6.000,00 sujeita a saldo: regra no centro, PostgreSQL e HTTP no anel externo.

Planta

Fluxo
Infraestrutura - gateway PostgreSQL e controller HTTPServiços de aplicação - useCaseFundsTransferServiços de domínio - fundsTransfer e InterfaceAccountGatewayModelo de domínio - Account, transferValidate, transferApplyAccount

Como 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.

  1. 1

    Account e funções puras validam e aplicam sem mutar

  2. 2

    O serviço de domínio declara o gateway por intenção (accountsLock, transferRecord)

  3. 3

    O serviço de aplicação abre a unidade de trabalho e devolve DTO

  4. 4

    A infraestrutura implementa o gateway no PostgreSQL e traduz em HTTP

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .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 onion-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 onion-db

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

Requisitos
BunDocker
Sobe junto
PostgreSQL

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

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

Domínio financeiro

  • Saldo

Padrões do catálogo que implementa

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • accounts
  • transfers

Variáveis de ambiente

ONION_DATABASE_URL
postgres://postgres:postgres@localhost:5432/onion_db
PostgreSQL behind the account gateway.

Parecidos

Por que se relacionam

Teste rápido

Qual destes combina com Arquitetura Onion?

Próximo projeto, ArquiteturaPeer-to-Peer
Esc

↑ ↓ navegarEnter abrir239 resultados