Pular para o conteúdo

Content Enricher

Completa a mensagem com dados de uma fonte externa antes de repassá-la. Inverso do Content Filter.

passos
4
arquivos
6
testes
0
tecnologias
6

Cenário

PIX cru chega só com accountId e amountCents; o enricher acrescenta titular, KYC e score de risco para o antifraude.

Planta

Sequência
5/5
evento cru (conta + valor)1entrega2GET /customers/:accountId3nome, KYC, score4evento enriquecido5Origempix-event-rawEnricherCadastro de clientespix-event-enriched
5

5 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.

  1. 1

    O evento cru entra em pix-event-raw

  2. 2

    Consulta GET /customers/:accountId

  3. 3

    Acrescenta campos do cliente, origem e enrichedAt

  4. 4

    Publica em pix-event-enriched antes do ack do cru

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

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

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec --user rabbitmq content-enricher-broker rabbitmq-diagnostics -q check_port_connectivity >/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 content-enricher-broker

Saída: PIX-001 cru com conta e valor; enriquecido com titular, kycStatus verified e riskScore 12.

Requisitos
BunDocker
Sobe junto
RabbitMQ

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

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

Domínio financeiro

  • PIX
  • Conta corrente
  • Antifraude
  • KYC

Padrões do catálogo que implementa

  • Content Enricher

Infraestrutura

  • RabbitMQmessage broker

    rabbitmq:3-alpine:5672

Variáveis de ambiente

CONTENT_ENRICHER_RABBITMQ_URL
amqp://guest:guest@localhost:5672
RabbitMQ of the enrichment pipeline.
CONTENT_ENRICHER_DIRECTORY_PORT
8113
Port of the customer directory the enricher queries (GET /customers/:accountId).

Parecidos

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Content Enricher?

Próximo projeto, Mensageria & EventosContent Filter
Esc

↑ ↓ navegarEnter abrir239 resultados