pattern/gof/proxy
- AbortSignal
- Bun
- ElysiaJS
- TypeScript
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.
pattern/gof/proxy
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ência9 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.
InterfaceAccountService é implementada pelo cliente real e pelo proxy
ProxyAccountService envolve o cliente real (ClientAccountCore)
Proteção primeiroConta de outro cliente nunca chega ao core
Cache com TTL de 30 s evita chamadas repetidas
Trade-offs
O que se ganha, o que se paga
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./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaí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.
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);
Nível
introdutório
1/13
Domínio financeiro
Padrões do catálogo que implementa
Trilhapasso 7 de 7
GoF — estrutura
Parecidos
Por que se relacionam
Seu progresso
0/157 estudados
Fica salvo só neste navegador.