npm package: @jinomdev/shared
Description: Shared utilities and types for billing microservices
Latest version: 1.0.3

# @jinomdev/shared

A comprehensive shared library for microservices architecture, providing common utilities, types, and patterns for distributed billing systems.

## Overview

This package contains reusable components designed to standardize functionality across multiple microservices. It includes service discovery, circuit breakers, message queuing, error handling, logging, and various utility functions.

## Installation

```bash
npm install @jinomdev/shared
# or
yarn add @jinomdev/shared
```

## Features

### 🔄 Service Discovery
- **Consul Integration**: Automatic service registration and discovery
- **Health Checks**: Built-in health monitoring
- **Load Balancing**: Service instance management

### ⚡ Circuit Breaker
- **Failure Protection**: Prevents cascading failures
- **Automatic Recovery**: Smart failure detection and recovery
- **Configurable Thresholds**: Customizable failure and success thresholds

### 📨 Message Queue
- **RabbitMQ Client**: Production-ready message queue integration
- **Event Types**: Standardized event definitions
- **Reliable Delivery**: Acknowledgment and retry mechanisms

### 🚨 Error Handling
- **Standardized Errors**: Common error types and codes
- **Error Handler**: Centralized error processing
- **Billing-Specific Codes**: Comprehensive payment and billing error codes

### 📊 HTTP Client
- **Enhanced Axios**: Wrapper with retry logic and timeouts
- **Correlation ID**: Request tracing across services
- **Circuit Breaker Integration**: Automatic failure protection

### 📝 Logger
- **Winston Integration**: Structured logging
- **Multiple Transports**: Console, file, and remote logging
- **Correlation Tracking**: Request correlation across services

### 🛠️ Utilities
- **Idempotency**: Duplicate request prevention
- **Money Operations**: Currency handling with precision
- **Correlation ID**: Distributed tracing support

## Quick Start

### Basic Usage

```typescript
import {
  ServiceRegistry,
  CircuitBreaker,
  Logger,
  HttpClient,
  RabbitMQClient
} from '@jinomdev/shared';

// Initialize logger
const logger = new Logger('my-service');

// Setup service discovery
const serviceRegistry = new ServiceRegistry({
  serviceName: 'user-service',
  serviceId: 'user-service-1',
  host: 'localhost',
  port: 3000,
  consulHost: 'localhost',
  consulPort: 8500
});

await serviceRegistry.register();
```

### Circuit Breaker Example

```typescript
import { CircuitBreaker } from '@jinomdev/shared';

const circuitBreaker = new CircuitBreaker('payment-service', {
  failureThreshold: 5,
  successThreshold: 2,
  timeout: 10000,
  resetTimeout: 30000
});

const result = await circuitBreaker.execute(async () => {
  return await paymentService.processPayment(paymentData);
});
```

### HTTP Client with Circuit Breaker

```typescript
import { HttpClient } from '@jinomdev/shared';

const httpClient = new HttpClient({
  baseURL: 'https://api.example.com',
  timeout: 5000,
  retries: 3,
  circuitBreaker: {
    failureThreshold: 3,
    resetTimeout: 30000
  }
});

const response = await httpClient.get('/users/123');
```

### Message Queue Integration

```typescript
import { RabbitMQClient, EventTypes } from '@jinomdev/shared';

const mqClient = new RabbitMQClient('amqp://localhost');
await mqClient.connect();

// Publishing events
await mqClient.publish('billing.payments', {
  type: EventTypes.PAYMENT_PROCESSED,
  data: {
    paymentId: '123',
    amount: 1000,
    currency: 'USD'
  }
});

// Consuming events
await mqClient.subscribe('billing.payments', (message) => {
  console.log('Payment event received:', message);
});
```

### Error Handling

```typescript
import { 
  BaseError, 
  BILLING_ERROR_CODES, 
  ValidationError,
  PaymentError 
} from '@jinomdev/shared';

// Custom error handling
try {
  await processPayment(paymentData);
} catch (error) {
  if (error.code === BILLING_ERROR_CODES.INSUFFICIENT_FUNDS) {
    // Handle insufficient funds
  } else if (error instanceof PaymentError) {
    // Handle payment-specific errors
  }
}
```

### Money Operations

```typescript
import { Money, MoneyUtils } from '@jinomdev/shared';

const price = new Money(1999, 'USD'); // $19.99
const tax = MoneyUtils.multiply(price, 0.08); // 8% tax
const total = MoneyUtils.add(price, tax);

console.log(MoneyUtils.format(total)); // "$21.59"
```

### Correlation ID Tracking

```typescript
import { CorrelationId, Logger } from '@jinomdev/shared';

// Generate correlation ID
const correlationId = CorrelationId.generate();

// Use with logger
const logger = new Logger('user-service');
logger.info('Processing request', { correlationId });

// Pass to HTTP requests
const response = await httpClient.get('/payments', {
  headers: {
    'X-Correlation-ID': correlationId
  }
});
```

## API Reference

### Service Discovery

#### ServiceRegistry

```typescript
interface ServiceConfig {
  serviceName: string;
  serviceId: string;
  host: string;
  port: number;
  consulHost: string;
  consulPort: number;
  healthCheckPath?: string;
}

class ServiceRegistry {
  constructor(config: ServiceConfig);
  register(): Promise<void>;
  deregister(): Promise<void>;
  discover(serviceName: string): Promise<ServiceInstance[]>;
}
```

### Circuit Breaker

```typescript
interface CircuitBreakerOptions {
  failureThreshold: number;
  successThreshold: number;
  timeout: number;
  resetTimeout: number;
}

class CircuitBreaker {
  constructor(name: string, options?: Partial<CircuitBreakerOptions>);
  execute<T>(fn: () => Promise<T>): Promise<T>;
  getState(): CircuitState;
}
```

### Types

#### Common Types

```typescript
interface Money {
  amount: number; // In smallest currency unit (cents)
  currency: string; // ISO 4217 currency code
}

interface PaginationQuery {
  page?: number;
  limit?: number;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}

interface ApiResponse<T> {
  success: boolean;
  data?: T;
  error?: {
    code: string;
    message: string;
  };
  pagination?: PaginationMeta;
}
```

### Error Codes

The library includes comprehensive error codes for billing operations:

```typescript
const BILLING_ERROR_CODES = {
  PAYMENT_FAILED: 'PAYMENT_FAILED',
  INSUFFICIENT_FUNDS: 'INSUFFICIENT_FUNDS',
  CARD_DECLINED: 'CARD_DECLINED',
  CARD_EXPIRED: 'CARD_EXPIRED',
  INVALID_CARD: 'INVALID_CARD',
  PAYMENT_METHOD_NOT_FOUND: 'PAYMENT_METHOD_NOT_FOUND',
  DUPLICATE_PAYMENT: 'DUPLICATE_PAYMENT',
  REFUND_FAILED: 'REFUND_FAILED',
  // ... and more
};
```

## Development

### Building

```bash
npm run build
# or
yarn build
```

### Testing

```bash
npm test
# or
yarn test
```

### Watch Mode

```bash
npm run watch
# or
yarn watch
```

## Architecture Patterns

This shared library implements several key microservices patterns:

### 1. Circuit Breaker Pattern
Prevents cascading failures by monitoring service calls and opening the circuit when failure thresholds are reached.

### 2. Service Discovery
Automatic service registration and discovery using Consul, enabling dynamic service location.

### 3. Correlation ID
Distributed request tracing across multiple services for debugging and monitoring.

### 4. Standardized Error Handling
Consistent error types and codes across all services for better error management.

### 5. Message-Driven Communication
Asynchronous communication between services using RabbitMQ for loose coupling.

## Best Practices

1. **Always use correlation IDs** for request tracing across services
2. **Implement circuit breakers** for external service calls
3. **Use standardized error codes** for consistent error handling
4. **Handle money with precision** using the Money utilities
5. **Register services** with health checks for proper service discovery
6. **Use structured logging** with correlation context

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## License

MIT License - see LICENSE file for details.

## Support

For issues and questions:
- Create an issue in the repository
- Check existing documentation
- Review code examples above

---

**Version**: 1.0.0  
**Maintained by**: Jinom Development Team