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

Proxy

Um substituto com a mesma interface do objeto real controla o acesso a ele: protege, guarda em cache, adia ou registra. Use quando chamar o objeto real é caro ou precisa de controle.

passos
4
arquivos
4
testes
0
tecnologias
4

Cenário

O app consulta o saldo de Maria três vezes: o core bancário é chamado uma vez só. A consulta da conta de João é recusada pelo proxy sem chegar ao core.

Planta

Sequência
9/9
balanceGet(Maria, 0001-5)1dona da conta? cache?2balanceGet (cache vazio)3GET /accounts/0001-5/balance4saldo5balanceGet(Maria, 0001-5)6saldo do cache, sem chamar o core7balanceGet(Maria, 0002-3)8recusado: conta de outro cliente9AppProxyAccountServiceClientAccountCoreCore bancário (HTTP)
9

9 passos — reproduza para seguir o fluxo

Como funciona

4passos

Um substituto com a mesma interface do objeto real controla o acesso a ele

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    InterfaceAccountService é implementada pelo cliente real e pelo proxy

  2. 2

    ProxyAccountService envolve o cliente real (ClientAccountCore)

  3. 3

    Proteção primeiroConta de outro cliente nunca chega ao core

  4. 4

    Cache com TTL de 30 s evita chamadas repetidas

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Controle de acesso e cache sem mudar o chamador

  • Objeto real não sabe do proxy

Custos

  • Uma camada a mais de indireção

  • Cache serve saldo com até 30 s de atraso

Código

pattern/gof/proxy

4 arquivos

./

  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar só Bun

  1. bun install# dependências
  2. bun run demo# roda o cenário

Saída: três leituras de R$ 15.230,42 com uma chamada ao core; a conta de João é recusada e o core segue com 1 chamada.

Requisitos
Bun

Código

src/demo.ts

// Demo: the app reads balances through a proxy with the same interface as the remote core-banking client; the proxy checks ownership and caches, the core is called only when needed.
import { Elysia } from "elysia";

type Balance = { accountId: string; balanceCents: number };

interface InterfaceAccountService {
  balanceGet(customerId: string, accountId: string): Promise<Balance>;
}

const CORE_URL = "http://localhost:4931";
const CORE_TIMEOUT_MS = 2_000;
const PROXY_CACHE_TTL_MS = 30_000;

// The remote core banking API: expensive to call, and it does not know who the customer is.
let coreCalls = 0;
const OWNERS: Record<string, string> = { "0001-5": "CUST-MARIA", "0002-3": "CUST-JOAO" };
const core = new Elysia()
  .get("/accounts/:accountId/balance", ({ params }) => (coreCalls++, { accountId: params.accountId, balanceCents: 1_523_042 }))
  .listen(new URL(CORE_URL).port);

// The real subject: a plain HTTP client of the core.
class ClientAccountCore implements InterfaceAccountService {
  async balanceGet(_customerId: string, accountId: string): Promise<Balance> {
    return (await fetch(`${CORE_URL}/accounts/${accountId}/balance`, { signal: AbortSignal.timeout(CORE_TIMEOUT_MS) })).json() as Promise<Balance>;
  }
}

// The proxy: same interface, wraps the real subject. Protection first (never call the core for someone else's account), then a short-lived cache.
class ProxyAccountService implements InterfaceAccountService {
  private readonly cache = new Map<string, { balance: Balance; expiresAt: number }>();

  constructor(private readonly subject: InterfaceAccountService, private readonly ttlMs: number) {}

  async balanceGet(customerId: string, accountId: string): Promise<Balance> {
    if (OWNERS[accountId] !== customerId) throw new Error(`${customerId} does not own ${accountId}`);
    const hit = this.cache.get(accountId);
    if (hit && hit.expiresAt > Date.now()) return hit.balance;
    const balance = await this.subject.balanceGet(customerId, accountId);
    this.cache.set(accountId, { balance, expiresAt: Date.now() + this.ttlMs });
    return balance;
  }
}

// The caller depends on the interface: it cannot tell the proxy from the real client.
const service: InterfaceAccountService = new ProxyAccountService(new ClientAccountCore(), PROXY_CACHE_TTL_MS);
for (let index = 0; index < 3; index++) {
  const { balanceCents } = await service.balanceGet("CUST-MARIA", "0001-5");
  console.log(`  [APP] Maria balance R$ ${(balanceCents / 100).toFixed(2)} (core calls so far: ${coreCalls})`);
}
await service.balanceGet("CUST-MARIA", "0002-3").catch((error: Error) => console.log(`  [PROXY] refused: ${error.message} (core calls: ${coreCalls})`));
await core.stop(true);

Relações

Onde ele se encaixa

Mapa
  1. Proxy

    Por que se relacionam

    Próximo projeto, GoFSingleton
    Esc

    ↑ ↓ navegarEnter abrir239 resultados