pattern/api/anti-corruption-layer
- Bun
- ElysiaJS
- MariaDB
- TypeScript
- mysql2
- Docker
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.
pattern/api/anti-corruption-layer
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
Fluxo6 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
accountLoad é a única porta do domínio
Reais → centavos, DD/MM/AAAA → ISO, letra → status do domínio
Disponível = saldo − bloqueio; status desconhecido → blocked
CD_RETORNO → ErrorAccountNotFound
Trade-offs
O que se ganha, o que se paga
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./
sql/
src/
Executar com Docker
./docker.shuntil docker exec anti-corruption-layer-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 anti-corruption-layer-dbSaí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.
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
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
Parecidos
Relações
Onde ele se encaixa
Por que se relacionam
Próximo passo
Teste rápido
Qual é o próximo passo depois de Anti-Corruption Layer?
Serviço autônomo por domínio. Abrir Microsserviços
Seu progresso
0/157 estudados
Fica salvo só neste navegador.