pattern/messaging/routing-slip
- Bun
- ElysiaJS
- TypeScript
O itinerário viaja na mensagem: cada etapa executa sua parte e encaminha ao próximo nome, sem orquestrador.
pattern/messaging/routing-slip
Cenário
Proposta de crédito passa por KYC, Score, Compliance e Comitê; o itinerário é montado na origem.
Planta
Fluxo5 passos — reproduza para seguir o fluxo
Como funciona
4passos
O itinerário viaja na mensagem e cada etapa encaminha ao próximo nome, sem orquestrador
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
Proposta com itinerary, stepIndexCurrent = 0 e replyTo
Etapa fora da posição atual responde 409
Executa a regra, anota em history e responde 202
Encaminha ao próximo ou envia a decisão ao replyTo
Trade-offs
O que se ganha, o que se paga
Vantagens
Sem orquestrador para cair
Caminho por mensagem com os mesmos serviços
Custos
Fluxo fixo depois do envio
Estado espalhado pelas etapas
Código
pattern/messaging/routing-slip
4 arquivos./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaída: envio fora de posição recusado com 409; PROP-001 passa por kyc → score 820 → compliance → committee approved.
Código
src/demo.ts// Demo: a credit proposal carries its own itinerary; each Elysia step does its part and forwards the slip to the next name.
import { Elysia } from "elysia";
const CREDIT_STEPS = ["kyc", "score", "compliance", "committee"] as const;
type CreditStep = (typeof CREDIT_STEPS)[number];
// One port per step in CREDIT_STEPS order, starting here; the origin has its own.
const CREDIT_STEP_PORT_FIRST = 8121;
const CREDIT_ORIGIN_PORT = 8120;
type CreditSlip = {
proposalId: string;
amountCents: number;
itinerary: CreditStep[];
// Position of the step that must handle the slip now.
stepIndexCurrent: number;
history: string[];
replyTo: string;
};
const stepUrl = (step: CreditStep) => `http://localhost:${CREDIT_STEP_PORT_FIRST + CREDIT_STEPS.indexOf(step)}/process`;
const STEP_RULES: Record<CreditStep, (slip: CreditSlip) => string> = {
kyc: (slip) => (slip.amountCents <= 50_000_000 ? "kyc approved" : "kyc rejected"),
score: (slip) => `score ${Math.max(300, 900 - Math.round(slip.amountCents / 100_000))}`,
compliance: () => "compliance clear",
committee: (slip) => (slip.history.includes("kyc approved") ? "committee approved" : "committee rejected"),
};
async function slipPost(url: string, slip: CreditSlip): Promise<number> {
return (await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(slip) })).status;
}
// Each step knows only its own rule: the next hop is read from the slip, never from a central orchestrator.
const steps = CREDIT_STEPS.map((step) =>
new Elysia()
.post("/process", ({ body, status }) => {
const slip = body as CreditSlip;
if (slip.itinerary[slip.stepIndexCurrent] !== step) return status(409, { error: "slip.step.out_of_position" });
const result = STEP_RULES[step](slip);
console.log(` [${step.toUpperCase()}] ${slip.proposalId}: ${result}`);
const next = { ...slip, stepIndexCurrent: slip.stepIndexCurrent + 1, history: [...slip.history, result] };
const nextStep = slip.itinerary[next.stepIndexCurrent];
queueMicrotask(() => void slipPost(nextStep ? stepUrl(nextStep) : slip.replyTo, next));
return status(202, { accepted: slip.proposalId });
})
.listen(CREDIT_STEP_PORT_FIRST + CREDIT_STEPS.indexOf(step)),
);
const decision = Promise.withResolvers<CreditSlip>();
const origin = new Elysia().post("/decisions", ({ body }) => (decision.resolve(body as CreditSlip), "ok")).listen(CREDIT_ORIGIN_PORT);
// The itinerary is decided once, at the origin, and travels inside the message.
const slip: CreditSlip = { proposalId: "PROP-001", amountCents: 8_000_000, itinerary: ["kyc", "score", "compliance", "committee"], stepIndexCurrent: 0, history: [], replyTo: `http://localhost:${CREDIT_ORIGIN_PORT}/decisions` };
console.log(` [ORIGIN] ${slip.proposalId} R$ ${(slip.amountCents / 100).toFixed(2)}: ${slip.itinerary.join(" → ")}`);
// A slip sent to a step out of its position is refused; the itinerary, not the sender, says who is next.
console.log(` [ORIGIN] sent to score out of position → HTTP ${await slipPost(stepUrl("score"), slip)}`);
await slipPost(stepUrl(slip.itinerary[0]!), slip);
console.log(` [ORIGIN] decision: ${(await decision.promise).history.join(" → ")}`);
for (const app of [...steps, origin]) await app.stop();
Nível
introdutório
1/13
Domínio financeiro
Padrões do catálogo que implementa
Parecidos
Por que se relacionam
Teste rápido
Qual destes combina com Routing Slip?
Etapas encadeadas pela própria mensagem. Abrir Pipes and Filters
Seu progresso
0/157 estudados
Fica salvo só neste navegador.