npm package: @takentrade/takentrade-libs
Description: TakeNTrade shared libraries
Author: Solomon Olatunji
Latest version: 4.0.9

# TakeNTrade Microservices Libraries

Shared libraries for the TakeNTrade microservices architecture, providing authentication, caching, messaging, notifications, resilience patterns, metrics, and common utilities.

## Installation

```bash
npm install @takentrade/takentrade-libs
```

## Quick Start

```typescript
import {
  CacheModule,
  MetricsModule,
  CircuitBreakerModule,
} from '@takentrade/takentrade-libs';

@Module({
  imports: [
    CacheModule.register(),
    MetricsModule.register({ defaultMetrics: true }),
    CircuitBreakerModule,
  ],
})
export class AppModule {}
```

## Modules

| Module             | Description                                    | Documentation                                  |
| ------------------ | ---------------------------------------------- | ---------------------------------------------- |
| **Authentication** | Route protection and role-based access control | [docs/auth.md](docs/auth.md)                   |
| **Cache**          | Redis-based caching with TTL support           | [docs/cache.md](docs/cache.md)                 |
| **BullMQ**         | Background job processing and queues           | [docs/bullmq.md](docs/bullmq.md)               |
| **NATS**           | Microservice messaging and event streaming     | [docs/nats.md](docs/nats.md)                   |
| **Notifications**  | Email, SMS, and push notifications             | [docs/notifications.md](docs/notifications.md) |
| **RPC**            | Request-response patterns for NATS             | [docs/rpc.md](docs/rpc.md)                     |
| **Resilience**     | Circuit breakers for fault tolerance           | [docs/resilience.md](docs/resilience.md)       |
| **Metrics**        | Prometheus metrics collection                  | [docs/metrics.md](docs/metrics.md)             |
| **Monitoring**     | Error tracking, alerting, uptime monitoring    | [docs/monitoring.md](docs/monitoring.md)       |
| **Common**         | Shared constants, enums, and utilities         | [docs/common.md](docs/common.md)               |
| **Utils**          | DTOs, pipes, filters, and helpers              | [docs/utils.md](docs/utils.md)                 |

## Features

### 🔐 Authentication & Authorization

- `@Public()` and `@Roles()` decorators
- JWT-based authentication support
- Role-based access control

### 💾 Caching

- Redis integration with ioredis
- TTL support
- Hash operations
- Auto-reconnection

### 📊 Metrics & Observability

- Prometheus metrics with prom-client
- Default process metrics (CPU, memory, event loop)
- Custom counters, gauges, histograms, summaries
- Circuit breaker metrics integration
- `/metrics` endpoint for scraping

### 🔄 Resilience

- Circuit breakers using Opossum
- Automatic failure detection
- Fallback support
- Health checks
- Request caching
- Comprehensive metrics

### 🚀 Background Jobs

- BullMQ integration
- Job scheduling and retries
- Delayed and repeatable jobs
- Progress tracking

### 📨 Messaging

- NATS integration
- Event patterns
- Request-response (RPC)
- Subject constants
- Automatic logging

### 📧 Notifications

- Email (verification, OTP, password reset, etc.)
- SMS notifications
- Push notifications
- Template support

## Environment Variables

```env
# Cache & BullMQ
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=your_password

# NATS
NATS_URL=nats://localhost:4222
NATS_SERVICE_QUEUE=service_queue

# JWT
JWT_SECRET=your_jwt_secret
```

## Usage Examples

### Cache

```typescript
await this.cacheService.set('key', 'value', 3600); // 1 hour TTL
const value = await this.cacheService.get('key');
```

### Metrics

```typescript
this.metricsService.registerCounter({
  name: 'requests_total',
  help: 'Total requests',
  labelNames: ['method', 'status'],
});
this.metricsService.incrementCounter('requests_total', {
  method: 'GET',
  status: '200',
});
```

### Circuit Breaker

```typescript
this.circuitBreaker.createBreaker('api', async (data) => this.apiCall(data), {
  timeout: 5000,
  errorThresholdPercentage: 50,
});
const result = await this.circuitBreaker.fire('api', requestData);
```

### Background Jobs

```typescript
await this.queue.add(
  'process-order',
  { orderId: '123' },
  {
    attempts: 3,
    backoff: { type: 'exponential', delay: 1000 },
  }
);
```

## Documentation

- [Authentication](docs/auth.md) - Route protection and RBAC
- [Cache](docs/cache.md) - Redis caching
- [BullMQ](docs/bullmq.md) - Background jobs
- [NATS](docs/nats.md) - Messaging
- [Notifications](docs/notifications.md) - Email, SMS, push
- [RPC](docs/rpc.md) - Request-response patterns
- [Resilience](docs/resilience.md) - Circuit breakers
- [Metrics](docs/metrics.md) - Prometheus metrics
- [Common](docs/common.md) - Shared utilities
- [Utils](docs/utils.md) - DTOs, pipes, filters

## Contributing

This is a private package for TakeNTrade microservices.

## License

Proprietary - See [LICENSE](LICENSE) file for details.

## Support

For issues or questions, contact the TakeNTrade development team.