Pular para o conteúdo
  1. Atlas
  2. GoF

Adapter

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.

passos
4
arquivos
7
testes
0
tecnologias
5

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ência
5/5
accountFind(0001234567-8)1SELECT MAINFRAME_CONTAS2TITULAR_NM, SALDO_CR, STATUS_CD, ULT_MOVTO3caixa, status, data ISO4Account5DomínioAdapterAccountMainframeMariaDB do mainframe
5

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

  1. 1

    InterfaceAccountGateway definida pelo domínio

  2. 2

    AdapterAccountMainframe implementa por composição

  3. 3

    ALICE MENDES → Alice Mendes, 20260901 → 2026-09-01, A → active

  4. 4

    Status desconhecido falha fechadoclosed

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .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 adapter-db healthcheck.sh --connect --innodb_initialized >/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 adapter-db

Saí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.

Requisitos
BunDocker
Sobe junto
MariaDB

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

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

Domínio financeiro

  • Conta corrente
  • PSP/Adquirente

Padrões do catálogo que implementa

  • Adapter

Infraestrutura

  • MariaDBbanco relacional

    mariadb:11:3306

Banco

sql/01_schema.sql

  • MAINFRAME_CONTAS

Variáveis de ambiente

ADAPTER_MAINFRAME_DATABASE_URL
mysql://app:app_password@localhost:3306/mainframe_db

Trilhapasso 1 de 7

GoF — estrutura

  1. 1Adapter
  2. 2Bridge
  3. 3Composite
  4. 4Decorator
  5. 5Facade
  6. 6Flyweight
  7. 7Proxy
Esc

↑ ↓ navegarEnter abrir239 resultados