pattern/gof/facade
- AbortSignal
- Bun
- ElysiaJS
- TypeScript
Interface única na frente de vários subsistemas: uma chamada do cliente, chamadas paralelas aos serviços, uma resposta. Só esconde quantos serviços existem e onde estão.
pattern/gof/facade
Cenário
O portal mostra conta e saldo, limite do cartão e investimentos com uma chamada em vez de três.
Planta
Fluxo4 passos — reproduza para seguir o fluxo
Como funciona
4passos
Interface única na frente de vários subsistemas, com chamadas paralelas e uma resposta
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
Só a facade conhece os endereços
Promise.all: latência da chamada mais lenta
AbortSignal.timeout por chamada
Só orquestra e agrega, sem regra
Trade-offs
O que se ganha, o que se paga
Vantagens
Uma chamada, sem acoplamento a endereços
Latência da mais lenta, não da soma
Custos
Mais um ponto de falha
Resposta única serve mal canais diferentes (use BFF)
Código
pattern/gof/facade
5 arquivos./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaída: 200 com conta (R$ 8.420,50 disponíveis), cartão (limite R$ 12.000,00, usado R$ 3.450,00) e duas posições de investimento numa resposta só.
Código
src/demo.ts// Demo: the bank portal makes one call; the facade asks three subsystems in parallel and returns one response.
import { Elysia } from "elysia";
// The subsystems only the facade knows, each its own HTTP service with its own route shape.
const URLS = { accounts: Bun.env.FACADE_ACCOUNTS_URL ?? "http://localhost:4041", cards: Bun.env.FACADE_CARDS_URL ?? "http://localhost:4042", investments: Bun.env.FACADE_INVESTMENTS_URL ?? "http://localhost:4043" };
const port = (url: string) => new URL(url).port;
const subsystems = [
new Elysia().get("/accounts/:id", () => ({ holderName: "Ana Beatriz Costa", availableCents: 842_050 })).listen(port(URLS.accounts)),
new Elysia().get("/credit/:id", () => ({ limitCents: 1_200_000, usedCents: 345_000, invoiceDueOn: "2026-10-15" })).listen(port(URLS.cards)),
new Elysia().get("/positions", () => [{ product: "CDB 110% CDI", amountCents: 2_000_000 }, { product: "Tesouro Selic 2029", amountCents: 1_520_000 }]).listen(port(URLS.investments)),
];
// Each call carries its own timeout: a slow subsystem fails fast instead of holding the portal.
const FACADE_SUBSYSTEM_TIMEOUT_MS = 800;
async function subsystemGet(url: string): Promise<unknown> {
const response = await fetch(url, { signal: AbortSignal.timeout(FACADE_SUBSYSTEM_TIMEOUT_MS) });
if (!response.ok) throw new Error(`${url} answered ${response.status}`);
return response.json();
}
// The facade orchestrates and aggregates only: latency is the slowest call, not the sum; every value comes as is.
const facade = new Elysia().get("/portal/:accountId", async ({ params: { accountId } }) => {
const [account, credit, positions] = await Promise.all([subsystemGet(`${URLS.accounts}/accounts/${accountId}`), subsystemGet(`${URLS.cards}/credit/${accountId}`), subsystemGet(`${URLS.investments}/positions?account=${accountId}`)]);
return { account, credit, positions };
});
const response = await facade.handle(new Request("http://localhost/portal/CC-0042"));
console.log(` [PORTAL] GET /portal/CC-0042 → ${response.status} ${await response.text()}`);
await Promise.all(subsystems.map((subsystem) => subsystem.stop(true)));
Nível
introdutório
0/13
Domínio financeiro
Padrões do catálogo que implementa
Variáveis de ambiente
Trilhapasso 5 de 7
GoF — estrutura
Por que se relacionam
Combina com
Teste rápido
Qual destes combina com Facade?
Uma fachada por cliente. Abrir Backend for Frontend
Seu progresso
0/157 estudados
Fica salvo só neste navegador.