Pular para o conteúdo

Anti-Corruption Layer

Camada de tradução entre o domínio e um sistema externo incompatível; o vocabulário do legado não sai dela. Use ao integrar core bancário, mainframe, bureau ou ERP.

passos
4
arquivos
7
testes
0
tecnologias
6

Cenário

Core dos anos 90 responde em CAIXA ALTA, reais decimais, DD/MM/AAAA, status de uma letra e bloqueio judicial separado, sempre HTTP 200 com CD_RETORNO.

Planta

Fluxo
6/6
Contexto do banco digitalAnti-Corruption LayerCore bancário legadoAccountcentavos, data ISO,saldo disponívelaccountLoadTradutoresreais para centavos,DD/MM/AAAA, statusCD_RETORNO paraexceção de domínioAPI HTTPCAIXA ALTA, sempre 200MariaDB
6

6 passos — reproduza para seguir o fluxo

Como funciona

4passos

Camada de tradução entre o domínio e um sistema externo incompatível, sem vazar o vocabulário do legado

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

  1. 1

    accountLoad é a única porta do domínio

  2. 2

    Reais → centavos, DD/MM/AAAA → ISO, letra → status do domínio

  3. 3

    Disponível = saldo − bloqueio; status desconhecido → blocked

  4. 4

    CD_RETORNO → ErrorAccountNotFound

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Domínio livre do legado

  • Trocar o core mexe só na ACL

Custos

  • Camada a manter a cada mudança do core

  • ACL pode acumular regra

Código

pattern/api/anti-corruption-layer

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 anti-corruption-layer-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 anti-corruption-layer-db

Saída: o core devolve VL_SALDO 12500.75, DT_ABERTURA 10/01/2020 e ST_CONTA A; o domínio recebe balanceCents 1250075, availableCents 1050075, openedOn 2020-01-10 e status active.

Requisitos
BunDocker
Sobe junto
MariaDB

Código

src/demo.ts

// Demo: the digital bank reads an account from the legacy core through the ACL; the core's model never leaves the layer.
import { Elysia } from "elysia";
import mysql from "mysql2/promise";

// The digital bank's own model: integer cents, ISO dates, the available balance as the product shows it.
type Account = { accountId: string; holderName: string; openedOn: string; status: "active" | "closed" | "blocked"; balanceCents: number; availableCents: number };
class ErrorAccountNotFound extends Error {
  override name = "ErrorAccountNotFound";
}

// The legacy core over MariaDB: CAIXA ALTA, reais as DECIMAL, "DD/MM/YYYY", always HTTP 200 with CD_RETORNO.
const CORE_URL = Bun.env.ANTI_CORRUPTION_LAYER_CORE_URL ?? "http://localhost:4011";
const pool = mysql.createPool({ uri: Bun.env.ANTI_CORRUPTION_LAYER_CORE_DATABASE_URL ?? "mysql://app:app_password@localhost:3306/legacy_core_db" });
const core = new Elysia().get("/CONTAS/:accountNumber", async ({ params }) => {
  const [rows] = await pool.query<mysql.RowDataPacket[]>("SELECT NR_CONTA, NM_CLIENTE, CAST(VL_SALDO AS CHAR) AS VL_SALDO, CAST(VL_BLOQUEADO AS CHAR) AS VL_BLOQUEADO, DT_ABERTURA, ST_CONTA FROM contas WHERE NR_CONTA = ?", [params.accountNumber]);
  return rows[0] ? { CD_RETORNO: "00", CONTA: rows[0] } : { CD_RETORNO: "08", DS_RETORNO: "CONTA INEXISTENTE" };
}).listen(new URL(CORE_URL).port);

// ---- Anti-corruption layer: the core's types and codes are declared here and never exported. ----
type CoreAccount = { NR_CONTA: string; NM_CLIENTE: string; VL_SALDO: string; VL_BLOQUEADO: string; DT_ABERTURA: string; ST_CONTA: string };
// "C" is congelada, a judicial block; an unknown code is read as blocked, never as a movable account.
const STATUS_FROM_CORE: Record<string, Account["status"]> = { A: "active", F: "closed", C: "blocked" };
const reaisToCents = (reais: string) => Number(reais.replace(".", ""));
const dateBrToIso = (dateBr: string) => dateBr.split("/").toReversed().join("-");

// The core keeps the judicial block apart from the balance; the domain shows what can actually be spent.
function accountFromCore(account: CoreAccount): Account {
  const balanceCents = reaisToCents(account.VL_SALDO);
  return {
    accountId: account.NR_CONTA,
    holderName: account.NM_CLIENTE,
    openedOn: dateBrToIso(account.DT_ABERTURA),
    status: STATUS_FROM_CORE[account.ST_CONTA] ?? "blocked",
    balanceCents,
    availableCents: Math.max(balanceCents - reaisToCents(account.VL_BLOQUEADO), 0),
  };
}

// The facade: the only way into the core; return codes become domain exceptions.
async function accountLoad(accountId: string): Promise<Account> {
  const reply = (await (await fetch(`${CORE_URL}/CONTAS/${encodeURIComponent(accountId)}`)).json()) as { CD_RETORNO: string; CONTA?: CoreAccount };
  if (reply.CD_RETORNO === "08") throw new ErrorAccountNotFound(`account ${accountId} not found`);
  return accountFromCore(reply.CONTA as CoreAccount);
}
// ---- end of the layer ----

console.log(`  [CORE]   ${JSON.stringify(await (await fetch(`${CORE_URL}/CONTAS/00012345`)).json())}`);
console.log(`  [DOMAIN] ${JSON.stringify(await accountLoad("00012345"))}`);
await core.stop(true);
await pool.end();

Nível

intermediário

4/13

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

Domínio financeiro

  • Conta corrente
  • Saldo

Padrões do catálogo que implementa

  • Anti-Corruption Layer

Infraestrutura

  • MariaDBbanco relacional

    mariadb:11:3306

Banco

sql/01_schema.sql

  • contas

Variáveis de ambiente

ANTI_CORRUPTION_LAYER_CORE_DATABASE_URL
mysql://app:app_password@localhost:3306/legacy_core_db
ANTI_CORRUPTION_LAYER_CORE_URL
http://localhost:4011

Parecidos

Esc

↑ ↓ navegarEnter abrir239 resultados