Pular para o conteúdo

Backend for Frontend (BFF)

Um backend por tipo de cliente: numa chamada, consulta os serviços em paralelo e devolve só o que a tela usa.

passos
4
arquivos
7
testes
0
tecnologias
7

Cenário

Home do app com primeiro nome, saldo disponível, três últimos lançamentos e próxima fatura, vindos do core e de cartões.

Planta

Sequência
5/5
par[em paralelo, timeout de 800 ms cada]GET /home/0042-11GET /accounts/0042-12GET /accounts/0042-1/statement3GET /accounts/0042-1/cards4primeiro nome, saldo disponível, 3 lançamentos, fatura5App mobileBFF mobilecore-bankingcards
5

5 passos — reproduza para seguir o fluxo

Como funciona

4passos

Um backend por tipo de cliente consulta os serviços em paralelo e devolve só o que a tela usa

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

Promise.allSettled+1
  1. 1

    Promise.allSettled com timeout por chamada

  2. 2

    Falha vira null e entra em unavailable

  3. 3

    Sem a conta, 502

  4. 4

    Projeção cortada para o canal; saldo disponível vem do core

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Uma chamada por tela, payload enxuto

  • Serviço fora deixa a tela parcial

Custos

  • Um serviço por canal

  • Regra pode migrar para o BFF

Código

pattern/api/bff

7 arquivos

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

sql/

  • 01_schema.sqlschema

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec bff-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f bff-db

Saída: 200 com firstName Maria, availableCents 375000, os 3 lançamentos mais recentes, fatura de 250000 com vencimento 2026-10-10 e unavailable vazio.

Requisitos
BunDocker
Sobe junto
PostgreSQL

Código

src/demo.ts

// Demo: the mobile BFF builds the app home in one call — core banking and cards in parallel, projected to what the screen uses.
import { Elysia } from "elysia";
import pg from "pg";

const pool = new pg.Pool({ connectionString: Bun.env.BFF_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/bff_db" });
const CORE_URL = Bun.env.BFF_CORE_URL ?? "http://localhost:4031";
const CARDS_URL = Bun.env.BFF_CARDS_URL ?? "http://localhost:4033";
const DOWNSTREAM_TIMEOUT_MS = 800;

type CoreAccount = { number: string; holderName: string; branch: string; availableCents: string };
type CoreStatementEntry = { description: string; amountCents: string; bookedAt: string };
type CardsCard = { lastDigits: string; brand: string; invoiceCents: string; invoiceDueOn: string };

// Downstream domain services: they know nothing about screens and expose their full records.
const core = new Elysia()
  .get("/accounts/:number", async ({ params }) => (await pool.query<CoreAccount>(`SELECT number, holder_name AS "holderName", branch, balance_cents - blocked_cents AS "availableCents" FROM accounts WHERE number = $1`, [params.number])).rows[0])
  .get("/accounts/:number/statement", async ({ params }) => (await pool.query<CoreStatementEntry>(`SELECT description, amount_cents AS "amountCents", booked_at AS "bookedAt" FROM statement_entries WHERE account_number = $1 ORDER BY booked_at DESC LIMIT 3`, [params.number])).rows)
  .listen(new URL(CORE_URL).port);
const cards = new Elysia().get("/accounts/:number/cards", async ({ params }) => (await pool.query<CardsCard>(`SELECT last_digits AS "lastDigits", brand, invoice_cents AS "invoiceCents", to_char(invoice_due_on, 'YYYY-MM-DD') AS "invoiceDueOn" FROM cards WHERE account_number = $1`, [params.number])).rows).listen(new URL(CARDS_URL).port);

// Each call has its own timeout; a failed one becomes null and the screen comes out partial instead of failing.
const downstreamGet = async <T>(url: string): Promise<T> => {
  const response = await fetch(url, { signal: AbortSignal.timeout(DOWNSTREAM_TIMEOUT_MS) });
  if (!response.ok) throw new Error(`downstream answered ${response.status}`);
  return (await response.json()) as T;
};
const settled = <T>(result: PromiseSettledResult<T>) => (result.status === "fulfilled" ? result.value : null);

// The mobile BFF: first name, what can be spent, three latest entries and the next invoice — nothing else.
const bffMobile = new Elysia().get("/home/:accountNumber", async ({ params, status }) => {
  const [accountResult, statementResult, cardsResult] = await Promise.allSettled([
    downstreamGet<CoreAccount>(`${CORE_URL}/accounts/${params.accountNumber}`),
    downstreamGet<CoreStatementEntry[]>(`${CORE_URL}/accounts/${params.accountNumber}/statement`),
    downstreamGet<CardsCard[]>(`${CARDS_URL}/accounts/${params.accountNumber}/cards`),
  ]);
  const [account, statement, cardList] = [settled(accountResult), settled(statementResult), settled(cardsResult)];
  if (!account) return status(502, { error: "account-unavailable" });
  return {
    firstName: account.holderName.split(" ")[0],
    availableCents: Number(account.availableCents),
    recent: (statement ?? []).map((entry) => ({ description: entry.description, amountCents: Number(entry.amountCents) })),
    invoice: cardList?.[0] ? { amountCents: Number(cardList[0].invoiceCents), dueOn: cardList[0].invoiceDueOn } : null,
    unavailable: [statement ? null : "statement", cardList ? null : "cards"].filter(Boolean),
  };
});

await pool.query("TRUNCATE cards, statement_entries, accounts");
await pool.query("INSERT INTO accounts (number, holder_name, branch, balance_cents, blocked_cents) VALUES ('0042-1', 'Maria Silva Souza', '0042', 425000, 50000)");
await pool.query("INSERT INTO statement_entries (account_number, description, amount_cents, booked_at) VALUES ('0042-1', 'PIX recebido', 50000, '2026-09-28'), ('0042-1', 'Supermercado', -12050, '2026-09-27'), ('0042-1', 'Salario', 500000, '2026-09-26'), ('0042-1', 'Aluguel', -180000, '2026-09-25')");
await pool.query("INSERT INTO cards (account_number, last_digits, brand, invoice_cents, invoice_due_on) VALUES ('0042-1', '4521', 'Visa', 250000, '2026-10-10')");
const response = await bffMobile.handle(new Request("http://localhost/home/0042-1"));
const text = await response.text();
console.log(`  [APP] GET /home/0042-1 → ${response.status} (${text.length} bytes) ${text}`);
await Promise.all([core.stop(true), cards.stop(true)]);
await pool.end();

Nível

intermediário

6/13

Linhas de TypeScript
49
Tipo
B — um serviço (docker.sh)

Domínio financeiro

  • PIX
  • Conta corrente
  • Saldo

Padrões do catálogo que implementa

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • accounts
  • statement_entries
  • cards

Variáveis de ambiente

BFF_DATABASE_URL
postgres://postgres:postgres@localhost:5432/bff_db
BFF_CORE_URL
http://localhost:4031
BFF_CARDS_URL
http://localhost:4033

Por que se relacionam

Teste rápido

Qual destes combina com Backend for Frontend?

Próximo projeto, API & IntegraçãoAPI Gateway
Esc

↑ ↓ navegarEnter abrir239 resultados