npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@mutualbank/pay-utils

v0.1.3

Published

MutualbankUtils - Queue adapters, shared utilities and domain entities

Readme

MutualbankUtils

Biblioteca compartilhada para os microsserviços do Motor de Pagamento. Contém adaptadores de fila, entidades de domínio, utilitários e integrações com provedores de pagamento.

Stack

  • Runtime: Node.js
  • Linguagem: TypeScript 5
  • Validação: Zod
  • Logging: Winston
  • Database: PostgreSQL (pg)
  • Mensageria: RabbitMQ (amqplib), AWS SQS (@aws-sdk/client-sqs)
  • HTTP Client: Axios

Estrutura

shared/
├── aplication/
│   ├── @types/              # Tipagens de provedores
│   ├── factory/             # Factories para Queue e Payment
│   └── interfaces/          # Contratos de serviços
├── domain/
│   ├── enums/               # Enums de filas e eventos
│   ├── errors/              # Classes de erro customizadas
│   ├── BaseDomain.ts        # Classe base para entidades
│   ├── Transaction.ts       # Entidade de transação
│   ├── ReceivedWebhookProvider.ts
│   └── RoutingAttempts.ts
├── infra/
│   ├── database/            # Conexão PostgreSQL
│   ├── queue/adapters/      # Adaptadores RabbitMQ e SQS
│   └── services/            # Serviços de pagamento e eventos
├── utils/                   # Utilitários (Logger, Document, PixKey)
└── index.ts                 # Exports públicos

Módulos

Queue Adapters

Suporte para RabbitMQ e AWS SQS com interface unificada.

import { QueueFactory } from 'mutualbankutils';

// Criação automática baseada em env vars
const queue = QueueFactory.createQueue();

// Ou configuração manual
const rabbitQueue = QueueFactory.create({
  type: 'rabbitmq',
  host: 'localhost',
  port: 5672,
  username: 'guest',
  password: 'guest',
  vhost: '/'
});

// Conexão
await queue.connect();

// Publicar mensagem
await queue.publish(EnumQueueName.PAYMENT_ORCHESTRATOR_PIX_IN, {
  externalId: 'tx-123',
  providerCode: 'A55',
  callbackUrls: ['https://callback.url'],
  payload: { /* dados */ }
});

// Consumir mensagens
await queue.consume(EnumQueueName.PAYMENT_ORCHESTRATOR_PIX_OUT, async (message) => {
  console.log(message.body);
  await queue.ack(message);
});

Filas Disponíveis

| Fila | Descrição | |------|-----------| | PAYMENT_ORCHESTRATOR_PIX_IN | Transações PIX de entrada | | PAYMENT_ORCHESTRATOR_PIX_OUT | Transações PIX de saída | | PAYMENT_ORCHESTRATOR_PIX_SEND_WEBHOOK | Envio de webhooks | | PAYMENT_ORCHESTRATOR_TRANSACTION_UPDATED | Atualizações de transação |

Domain Entities

Transaction

import { Transaction, TransactionType, PaymentMethod } from 'mutualbankutils';

const transaction = Transaction.create({
  amount: 10000,
  type: TransactionType.PIX_IN,
  providerCode: 'A55',
  externalId: 'ext-123',
  method: PaymentMethod.PIX,
  client: 'client-id'
});

// Status transitions
transaction.pending();
transaction.processing();
transaction.completed();
transaction.failed();
transaction.cancelled();
transaction.refunded();

// Acesso aos dados
const status = transaction.get('status');
const payload = transaction.payload();

Status de Transação

| Status | Descrição | |--------|-----------| | created | Transação criada | | pending | Aguardando processamento | | processing | Em processamento | | completed | Concluída com sucesso | | failed | Falha no processamento | | cancelled | Cancelada | | refunded | Estornada |

Payment Processors

Factory para criar processadores de pagamento por provedor.

import { PaymentProcessorFactory } from 'mutualbankutils';

const processor = PaymentProcessorFactory.create('A55');
// ou
const processor = PaymentProcessorFactory.create('PAYZU');

Provedores suportados:

  • A55 - Integração com A55
  • PAYZU - Integração com Payzu
  • FAKE - Mock para testes

Errors

Classes de erro customizadas para tratamento padronizado.

import { NotFound, NotSupported, UnauthorizedAccess, BaseError } from 'mutualbankutils';

throw new NotFound('Transaction not found');
throw new NotSupported('Feature not supported');
throw new UnauthorizedAccess('Invalid credentials');

Utils

Logger

import { Logger } from 'mutualbankutils/shared/utils/Logger';

Logger.info('Mensagem informativa', { transactionId: '123' });
Logger.warn('Aviso', { context: 'webhook' });
Logger.error('Erro crítico', { error: err });
Logger.debug('Debug info', { data: payload });

Document

Validação de CPF e CNPJ.

import { Document } from 'mutualbankutils/shared/utils/Document';

Document.validateCPF('123.456.789-09'); // true/false
Document.validateCNPJ('12.345.678/0001-90'); // true/false

PixKey

Identificação e formatação de chaves PIX.

import { PixKey } from 'mutualbankutils/shared/utils/PixKey';

// Identificar tipo da chave
PixKey.identifyPixKey('123.456.789-09'); // 'cpf'
PixKey.identifyPixKey('[email protected]'); // 'email'
PixKey.identifyPixKey('11999999999'); // 'phone'

// Formatar chave
PixKey.formatPixKey('(11) 99999-9999'); // '5511999999999'

Variáveis de Ambiente

Queue

| Variável | Descrição | Default | |----------|-----------|---------| | QUEUE_TYPE | Tipo de fila (rabbitmq, sqs) | sqs |

RabbitMQ

| Variável | Descrição | Default | |----------|-----------|---------| | RABBITMQ_HOST | Host do RabbitMQ | localhost | | RABBITMQ_PORT | Porta | 5672 | | RABBITMQ_USER | Usuário | guest | | RABBITMQ_PASSWORD | Senha | guest | | RABBITMQ_VHOST | Virtual Host | / |

AWS SQS

| Variável | Descrição | Default | |----------|-----------|---------| | SQS_ENDPOINT | Endpoint SQS | - | | SQS_REGION | Região AWS | us-east-1 | | SQS_ACCESS_KEY | Access Key | - | | SQS_SECRET_KEY | Secret Key | - |

Logger

| Variável | Descrição | Default | |----------|-----------|---------| | SERVICE_NAME | Nome do serviço para logs | - | | LOG_LEVEL | Nível de log | info |

Instalação

npm install
npm run build

Scripts

| Comando | Descrição | |---------|-----------| | npm run build | Compila TypeScript para dist/ |

Uso nos Microsserviços

// Import direto do dist
import { 
  Transaction, 
  QueueFactory, 
  NotFound,
  EnumQueueName 
} from '../lib/MutualbankUtils/dist';

// Import de utils específicos
import { Logger } from '../lib/MutualbankUtils/shared/utils/Logger';