Pular para o conteúdo

Micro-Frontends

Cada time entrega uma fatia vertical (fragmento de tela + backend) com deploy próprio; um shell compõe a página e uma fatia fora vira aviso no lugar dela.

passos
4
arquivos
4
testes
0
tecnologias
4

Cenário

Tela da conta com extrato (contas) e investimentos (wealth); investimentos cai e o extrato segue visível.

Planta

Sequência
5/5
par[fragmentos em paralelo, cada um com timeout]GET /accounts/CC-11GET /fragment2GET /fragment3fora do ar4página com fallback no lugar de investimentos5ClienteShellMFE Extrato (time de contas)MFE Investimentos (time de wealth)
5

5 passos — reproduza para seguir o fluxo

Como funciona

4passos

Cada time entrega uma fatia vertical (fragmento de tela + backend) com deploy próprio

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

AbortSignal.timeout+2
  1. 1

    Cada micro-frontend é um Elysia que devolve <section data-mfe="nome">

  2. 2

    O shell busca em paralelo, com AbortSignal.timeout

  3. 3

    Erro ou timeoutFallback no lugar do fragmento

  4. 4

    A página custa o fragmento mais lento, limitado pelo timeout

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Deploy independente por fatia

  • Falha degrada só o trecho

Custos

  • Mais servidores e pipelines

  • Consistência visual exige design system

Código

pattern/architecture/micro-frontends

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: com as duas fatias no ar, extrato e investimentos; com investimentos fora, o extrato segue e investimentos mostra “Indisponível no momento”.

Requisitos
Bun

Código

src/demo.ts

// Demo: the account page is composed by a shell from fragments served by two teams on their own servers; one goes down, the page stays up.
import { Elysia } from "elysia";

// Each micro-frontend is its own server and deploy; the contract with the shell is one root element named after it.
const fragmentServe = (name: string, inner: string) =>
  new Elysia().get("/fragment", ({ set }) => {
    set.headers["content-type"] = "text/html; charset=utf-8";
    return `<section data-mfe="${name}">${inner}</section>`;
  }).listen(0);

const statement = fragmentServe("statement", "<ul><li>PIX para maria@banco.com.br −R$ 250,00</li></ul>");
const investments = fragmentServe("investments", "<p>Tesouro Selic 2029 R$ 15.000,00</p>");
const routes = [
  { name: "statement", url: `http://localhost:${statement.server!.port}` },
  { name: "investments", url: `http://localhost:${investments.server!.port}` },
];

const FRAGMENT_TIMEOUT_MS = 300;

// Shell: fetches fragments in parallel, each with its own timeout; an error or a slow fragment becomes a fallback.
// The page costs the slowest fragment capped by the timeout, never the sum.
const shell = new Elysia().get("/accounts/:accountId", async ({ set }) => {
  const fragments = await Promise.all(
    routes.map((route) =>
      fetch(`${route.url}/fragment`, { signal: AbortSignal.timeout(FRAGMENT_TIMEOUT_MS) }).then(
        (response) => response.text(),
        () => `<section data-mfe="${route.name}" data-status="unavailable"><p>Indisponível no momento</p></section>`,
      ),
    ),
  );
  set.headers["content-type"] = "text/html; charset=utf-8";
  return `<main>${fragments.join("")}</main>`;
});

async function pagePrint(label: string): Promise<void> {
  const html = await (await shell.handle(new Request("http://localhost/accounts/CC-1"))).text();
  console.log(`  [SHELL] ${label}`);
  for (const match of html.matchAll(/<section data-mfe="(\w+)"[^>]*>(.*?)<\/section>/g)) console.log(`    ${match[1]?.padEnd(12)} ${match[2]?.replace(/<[^>]+>/g, " ").trim()}`);
}

await pagePrint("both teams up");
await investments.stop(true);
await pagePrint("investments team down: the page renders with its fallback");
await statement.stop(true);

Nível

introdutório

1/13

Linhas de TypeScript
38
Tipo
A — código puro

Domínio financeiro

  • PIX
  • Conta corrente
  • Extrato
  • Investimentos

Padrões do catálogo que implementa

  • Micro-Frontends

Por que se relacionam

Teste rápido

Qual destes combina com Micro-Frontends?

Próximo projeto, ArquiteturaMicrokernel (Arquitetura de Plugins)
Esc

↑ ↓ navegarEnter abrir239 resultados