pattern/messaging/content-enricher
- Bun
- ElysiaJS
- RabbitMQ
- TypeScript
- amqplib
- Docker
Completa a mensagem com dados de uma fonte externa antes de repassá-la. Inverso do Content Filter.
pattern/messaging/content-enricher
Cenário
PIX cru chega só com accountId e amountCents; o enricher acrescenta titular, KYC e score de risco para o antifraude.
Planta
Sequência5 passos — reproduza para seguir o fluxo
Como funciona
4passos
Completa a mensagem com dados de uma fonte externa antes de repassá-la
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
O evento cru entra em pix-event-raw
Consulta GET /customers/:accountId
Acrescenta campos do cliente, origem e enrichedAt
Publica em pix-event-enriched antes do ack do cru
Trade-offs
O que se ganha, o que se paga
Vantagens
Produtor envia só o que sabe
Consumidor decide sem buscar dados
Custos
Uma chamada externa por mensagem
Fonte fora trava o pipeline
Código
pattern/messaging/content-enricher
6 arquivos./
src/
Executar com Docker
./docker.shuntil docker exec --user rabbitmq content-enricher-broker rabbitmq-diagnostics -q check_port_connectivity >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f content-enricher-brokerSaída: PIX-001 cru com conta e valor; enriquecido com titular, kycStatus verified e riskScore 12.
Código
src/demo.ts// Demo: a raw PIX event (account + amount) is enriched from the customer directory before it reaches antifraud.
import amqplib from "amqplib";
import { Elysia } from "elysia";
const PIX_RAW_QUEUE = "pix-event-raw";
const PIX_ENRICHED_QUEUE = "pix-event-enriched";
const DIRECTORY_PORT = Number(Bun.env.CONTENT_ENRICHER_DIRECTORY_PORT ?? 8113);
type PixEventRaw = { pixId: string; accountId: string; amountCents: number };
type Customer = { holderName: string; kycStatus: string; riskScore: number };
// The external source of the pattern: a customer directory answering over HTTP.
const directory = new Elysia()
.get("/customers/:accountId", ({ params, status }) =>
params.accountId === "ACC-2001" ? { holderName: "Ana Beatriz Souza", kycStatus: "verified", riskScore: 12 } : status(404, { error: "customer.unknown" }),
)
.listen(DIRECTORY_PORT);
const connection = await amqplib.connect(Bun.env.CONTENT_ENRICHER_RABBITMQ_URL ?? "amqp://guest:guest@localhost:5672");
const channel = await connection.createChannel();
for (const queue of [PIX_RAW_QUEUE, PIX_ENRICHED_QUEUE]) {
await channel.assertQueue(queue, { durable: true });
await channel.purgeQueue(queue);
}
// Enricher: adds the customer fields, then acks the raw event only after the enriched one is published.
await channel.consume(PIX_RAW_QUEUE, async (message) => {
if (!message) return;
const raw = JSON.parse(message.content.toString()) as PixEventRaw;
const customer = (await (await fetch(`http://localhost:${DIRECTORY_PORT}/customers/${raw.accountId}`)).json()) as Customer;
const enriched = { ...raw, ...customer, enrichedFrom: "customer-directory", enrichedAt: new Date().toISOString() };
channel.sendToQueue(PIX_ENRICHED_QUEUE, Buffer.from(JSON.stringify(enriched)), { persistent: true });
channel.ack(message);
});
const raw: PixEventRaw = { pixId: "PIX-001", accountId: "ACC-2001", amountCents: 85_000 };
channel.sendToQueue(PIX_RAW_QUEUE, Buffer.from(JSON.stringify(raw)), { persistent: true });
console.log(` [RAW] ${JSON.stringify(raw)}`);
for (let i = 0; i < 100; i++) {
const message = await channel.get(PIX_ENRICHED_QUEUE, { noAck: true });
if (message) {
console.log(` [ENRICHED] ${message.content.toString()}`);
break;
}
await Bun.sleep(50);
}
await connection.close();
await directory.stop();
Nível
introdutório
3/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
RabbitMQmessage broker
rabbitmq:3-alpine:5672
Variáveis de ambiente
Parecidos
Relações
Onde ele se encaixa
Por que se relacionam
Vem antes
Próximo passo
Alternativa a
Teste rápido
Qual é o próximo passo depois de Content Enricher?
Junta o resultado. Abrir Aggregator
Seu progresso
0/157 estudados
Fica salvo só neste navegador.