pattern/gof/adapter
- Bun
- MariaDB
- TypeScript
- mysql2
- Docker
Envolve um sistema externo numa interface definida pelo domínio, traduzindo campos, unidades, datas e códigos. Use para integrar mainframe, PSP ou terceiro sem vazar a convenção deles.
pattern/gof/adapter
Cenário
O mainframe usa caixa alta, centavos, data YYYYMMDD e status de uma letra; o domínio lê a conta no próprio formato.
Planta
Sequência5 passos — reproduza para seguir o fluxo
Como funciona
4passos
Envolve um sistema externo numa interface definida pelo domínio, traduzindo campos, unidades, datas e códigos
Esconde cada passo: lembre antes de tocar para revelar.
InterfaceAccountGateway definida pelo domínio
AdapterAccountMainframe implementa por composição
ALICE MENDES → Alice Mendes, 20260901 → 2026-09-01, A → active
Status desconhecido falha fechadoclosed
Trade-offs
O que se ganha, o que se paga
Vantagens
Domínio sem convenção do fornecedor
Troca de fornecedor muda só o adapter
Custos
Mapeamento extra por campo
Adapter pode acumular regra
Código
pattern/gof/adapter
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec adapter-db healthcheck.sh --connect --innodb_initialized >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f adapter-dbSaída: a linha crua do mainframe (ALICE MENDES, SALDO_CR 1250000, A, 20260901) e a conta do domínio: Alice Mendes, balanceCents 1250000, active, 2026-09-01.
Código
src/demo.ts// Demo: the domain reads an account through its own interface; the adapter translates the legacy mainframe layout.
import mysql from "mysql2/promise";
// The contract the domain owns: domain names, cents with the unit in the name, ISO dates and a closed set of statuses.
type AccountStatus = "active" | "blocked" | "closed";
type Account = { accountId: string; holderName: string; balanceCents: number; status: AccountStatus; lastMovementOn: string };
interface InterfaceAccountGateway {
accountFind(accountId: string): Promise<Account | undefined>;
}
// The mainframe cannot change: uppercase fields, cents as INT, YYYYMMDD dates and one-letter statuses.
type LegacyAccount = { CONTA_NR: string; TITULAR_NM: string; SALDO_CR: number; STATUS_CD: string; ULT_MOVTO: string };
const STATUS_MAP: Record<string, AccountStatus> = { A: "active", B: "blocked", E: "closed" };
const titleCase = (name: string) => name.split(" ").filter(Boolean).map((part) => part.charAt(0) + part.slice(1).toLowerCase()).join(" ");
// Object adapter: implements the domain interface by composition; every mainframe convention is translated here and nowhere else.
class AdapterAccountMainframe implements InterfaceAccountGateway {
constructor(private readonly pool: mysql.Pool) {}
async accountFind(accountId: string): Promise<Account | undefined> {
const [rows] = await this.pool.query<mysql.RowDataPacket[]>("SELECT CONTA_NR, TITULAR_NM, SALDO_CR, STATUS_CD, ULT_MOVTO FROM MAINFRAME_CONTAS WHERE CONTA_NR = ?", [accountId]);
const legacy = rows[0] as LegacyAccount | undefined;
if (!legacy) return undefined;
return {
accountId: legacy.CONTA_NR,
holderName: titleCase(legacy.TITULAR_NM),
balanceCents: legacy.SALDO_CR,
// Fail closed: a status the adapter does not know is closed, never active.
status: STATUS_MAP[legacy.STATUS_CD] ?? "closed",
lastMovementOn: `${legacy.ULT_MOVTO.slice(0, 4)}-${legacy.ULT_MOVTO.slice(4, 6)}-${legacy.ULT_MOVTO.slice(6, 8)}`,
};
}
}
const pool = mysql.createPool({ uri: Bun.env.ADAPTER_MAINFRAME_DATABASE_URL ?? "mysql://app:app_password@localhost:3306/mainframe_db" });
const [legacyRows] = await pool.query("SELECT * FROM MAINFRAME_CONTAS WHERE CONTA_NR = '0001234567-8'");
console.log(` [MAINFRAME] ${JSON.stringify(legacyRows)}`);
const gateway: InterfaceAccountGateway = new AdapterAccountMainframe(pool);
console.log(` [DOMAIN] ${JSON.stringify(await gateway.accountFind("0001234567-8"))}`);
await pool.end();
Nível
intermediário
4/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
MariaDBbanco relacional
mariadb:11:3306
Banco
sql/01_schema.sql
Variáveis de ambiente
Trilhapasso 1 de 7
GoF — estrutura
Por que se relacionam
Combina com
Teste rápido
Qual destes combina com Adapter?
Converte cada formato de entrada. Abrir Normalizer
Seu progresso
0/157 estudados
Fica salvo só neste navegador.