Pular para o conteúdo

Normalizer

Converte mensagens de fontes heterogêneas para um formato canônico; um tradutor por origem, o downstream conhece só o canônico.

passos
4
arquivos
6
testes
0
tecnologias
5

Cenário

Dois PSPs notificam o mesmo PIX em formatos próprios; o processamento recebe centavos inteiros e horário UTC.

Planta

Fluxo
4/4
PSP Alfa: snake_case,centavos, UTCpix.psp.native(routing key = PSP)PSP Gama: abreviado,1.250,90, horário deBrasíliaNormalizer:tradutor por origempix-transfer-canonical
4

4 passos — reproduza para seguir o fluxo

Como funciona

4passos

Converte mensagens de fontes heterogêneas para um formato canônico, com um tradutor por origem

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    Cada PSP publica o payload nativo com sua routing key

  2. 2

    O normalizer escolhe o tradutor pela routing key

  3. 3

    Converte valor para centavos e horário para UTC

  4. 4

    Publica em pix-transfer-canonical antes do ack

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Downstream não conhece formato nativo

  • Nova fonte não muda consumidores

Custos

  • Um tradutor por fonte

  • Ponto central do fluxo

Código

pattern/messaging/normalizer

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 normalizer-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 normalizer-broker

Saída: psp-alfa (centavos, UTC) e psp-gama (1.250,90, horário de Brasília) viram o mesmo canônico: 125090 centavos, 2026-03-01T13:45:30.000Z.

Requisitos
BunDocker
Sobe junto
RabbitMQ

Código

src/demo.ts

// Demo: two PSPs report the same PIX in their own formats; the normalizer converts both into one canonical transfer.
import amqplib from "amqplib";

const PIX_NATIVE_EXCHANGE = "pix.psp.native";
const PIX_INBOUND_QUEUE = "pix-normalizer-inbound";
const PIX_CANONICAL_QUEUE = "pix-transfer-canonical";

type PixTransferCanonical = { transferId: string; amountCents: number; occurredAt: string; sourcePsp: string };

// One translator per source; cents as integers and instants in UTC, so downstream never sees a native format.
const translators: Record<string, (raw: Record<string, string | number>) => Omit<PixTransferCanonical, "sourcePsp">> = {
  // snake_case, amount in cents, ISO 8601 in UTC.
  "psp-alfa": (raw) => ({ transferId: String(raw.pix_id), amountCents: Number(raw.valor_centavos), occurredAt: new Date(String(raw.data_hora)).toISOString() }),
  // abbreviated, "1.250,90" parsed from the string (never through a float), local Brasília time UTC−03:00.
  "psp-gama": (raw) => {
    const [date = "", time = ""] = String(raw.dt).split(" ");
    const [day, month, year] = date.split("/");
    return { transferId: String(raw.id), amountCents: Number(String(raw.val).replaceAll(".", "").replace(",", "")), occurredAt: new Date(`${year}-${month}-${day}T${time}-03:00`).toISOString() };
  },
};

const connection = await amqplib.connect(Bun.env.NORMALIZER_RABBITMQ_URL ?? "amqp://guest:guest@localhost:5672");
const channel = await connection.createChannel();
await channel.assertExchange(PIX_NATIVE_EXCHANGE, "direct", { durable: true });
await channel.assertQueue(PIX_INBOUND_QUEUE, { durable: true });
await channel.assertQueue(PIX_CANONICAL_QUEUE, { durable: true });
// The routing key is the source: the normalizer learns who sent the message from it.
for (const source of Object.keys(translators)) await channel.bindQueue(PIX_INBOUND_QUEUE, PIX_NATIVE_EXCHANGE, source);
for (const queue of [PIX_INBOUND_QUEUE, PIX_CANONICAL_QUEUE]) await channel.purgeQueue(queue);

await channel.consume(PIX_INBOUND_QUEUE, (message) => {
  if (!message) return;
  const sourcePsp = message.fields.routingKey;
  const canonical = { ...translators[sourcePsp]!(JSON.parse(message.content.toString())), sourcePsp };
  channel.sendToQueue(PIX_CANONICAL_QUEUE, Buffer.from(JSON.stringify(canonical)), { persistent: true });
  channel.ack(message);
});

// The same R$ 1.250,90 transfer at 13:45:30 UTC, as each PSP sends it.
const natives = {
  "psp-alfa": { pix_id: "PIX-1", valor_centavos: 125_090, data_hora: "2026-03-01T13:45:30.000Z" },
  "psp-gama": { id: "PIX-1", val: "1.250,90", dt: "01/03/2026 10:45:30" },
};
for (const [psp, body] of Object.entries(natives)) {
  channel.publish(PIX_NATIVE_EXCHANGE, psp, Buffer.from(JSON.stringify(body)), { persistent: true });
  console.log(`  [${psp}] ${JSON.stringify(body)}`);
}

for (let received = 0, i = 0; received < 2 && i < 100; i++) {
  const message = await channel.get(PIX_CANONICAL_QUEUE, { noAck: true });
  if (message) {
    received++;
    console.log(`  [CANONICAL] ${message.content.toString()}`);
  } else await Bun.sleep(50);
}

await connection.close();

Nível

introdutório

3/13

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

Domínio financeiro

  • PIX
  • PSP/Adquirente

Padrões do catálogo que implementa

Infraestrutura

  • RabbitMQmessage broker

    rabbitmq:3-alpine:5672

Variáveis de ambiente

NORMALIZER_RABBITMQ_URL
amqp://guest:guest@localhost:5672
RabbitMQ of the normalizer.

Por que se relacionam

Teste rápido

Qual destes combina com Normalizer?

Próximo projeto, Mensageria & EventosPoint-to-Point
Esc

↑ ↓ navegarEnter abrir239 resultados