npm package: @katdev/transports
Description: Multi-transport configuration for NestJS microservices - HTTP, gRPC, TCP, RabbitMQ, NATS
Latest version: 1.0.0

# @katdev/transports

Multi-transport configuration for NestJS microservices. Easily configure HTTP, gRPC, TCP, RabbitMQ, and NATS transports with a unified API.

## Features

✅ **Multiple Transports** - HTTP, gRPC, TCP, RabbitMQ, NATS  
✅ **Hybrid Applications** - Run multiple transports in a single service  
✅ **Service Discovery Integration** - Auto-register with service registry  
✅ **Environment-based Configuration** - Enable/disable transports via env vars  
✅ **Type Safe** - Full TypeScript support  
✅ **Production Ready** - Used in production microservices  

## Installation

```bash
npm install @katdev/transports
```

### Optional Transport Dependencies

Install only what you need:

```bash
# For gRPC
npm install @grpc/grpc-js @grpc/proto-loader

# For RabbitMQ
npm install amqplib amqp-connection-manager

# For NATS
npm install nats
```

## Quick Start

### 1. Configure Environment Variables

```env
# Service Identity
SERVICE_NAME=user

# HTTP Transport
TRANSPORT_HTTP_ENABLED=true
HTTP_PORT=3003
HTTP_GLOBAL_PREFIX=api/v1
CORS_ORIGIN=*

# gRPC Transport
TRANSPORT_GRPC_ENABLED=true
GRPC_PORT=5003

# RabbitMQ (optional)
TRANSPORT_RMQ_ENABLED=false
RMQ_URLS=amqp://localhost:5672
RMQ_QUEUE=user_queue

# NATS (optional)
TRANSPORT_NATS_ENABLED=false
NATS_SERVERS=nats://localhost:4222
```

### 2. Bootstrap Your Service

```typescript
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { ServiceDiscoveryClientImpl } from '@katdev/service-discovery';
import {
  createHttpConfig,
  createGrpcConfig,
  createRmqConfig,
  configureApplication,
  startApplication,
} from '@katdev/transports';
import { join } from 'path';

async function bootstrap() {
  const configService = new ConfigService();

  // Create NestJS app
  const app = await NestFactory.create(AppModule);

  // Get service discovery client
  const discoveryClient = app.get(ServiceDiscoveryClientImpl);

  // Build transport configuration
  const transportConfig = {
    serviceName: configService.get('SERVICE_NAME', 'user'),
    transports: [
      // HTTP
      createHttpConfig(configService),
      
      // gRPC
      createGrpcConfig(
        configService,
        join(__dirname, './user.proto'),
        'user'
      ),
      
      // RabbitMQ
      createRmqConfig(configService, 'user_queue'),
    ],
  };

  // Configure and register transports
  const { transports } = await configureApplication(
    app,
    transportConfig,
    discoveryClient
  );

  // Start all transports
  await startApplication({ app, transports });

  console.log('🚀 Service started with transports:', transports);
}

bootstrap();
```

## Transport Configurations

### HTTP Transport

```typescript
import { createHttpConfig } from '@katdev/transports';

const httpConfig = createHttpConfig(configService, {
  port: 3000,
  globalPrefix: 'api/v1',
  cors: {
    origin: '*',
    credentials: true,
  },
});
```

**Environment Variables:**
```env
TRANSPORT_HTTP_ENABLED=true
HTTP_PORT=3000
HTTP_HOST=0.0.0.0
HTTP_GLOBAL_PREFIX=api/v1
CORS_ORIGIN=*
CORS_CREDENTIALS=true
```

### gRPC Transport

```typescript
import { createGrpcConfig } from '@katdev/transports';
import { join } from 'path';

const grpcConfig = createGrpcConfig(
  configService,
  join(__dirname, './proto/user.proto'),
  'user'
);
```

**Environment Variables:**
```env
TRANSPORT_GRPC_ENABLED=true
GRPC_PORT=5000
GRPC_HOST=0.0.0.0
```

### TCP Transport

```typescript
import { createTcpConfig } from '@katdev/transports';

const tcpConfig = createTcpConfig(configService);
```

**Environment Variables:**
```env
TRANSPORT_TCP_ENABLED=true
TCP_PORT=4000
TCP_HOST=0.0.0.0
TCP_RETRY_ATTEMPTS=3
TCP_RETRY_DELAY=3000
```

### RabbitMQ Transport

```typescript
import { createRmqConfig } from '@katdev/transports';

const rmqConfig = createRmqConfig(configService, 'my_queue');
```

**Environment Variables:**
```env
TRANSPORT_RMQ_ENABLED=true
RMQ_URLS=amqp://localhost:5672
RMQ_QUEUE=my_queue
RMQ_DURABLE=true
RMQ_PREFETCH_COUNT=10
```

### NATS Transport

```typescript
import { createNatsConfig } from '@katdev/transports';

const natsConfig = createNatsConfig(configService);
```

**Environment Variables:**
```env
TRANSPORT_NATS_ENABLED=true
NATS_SERVERS=nats://localhost:4222
NATS_QUEUE=my_queue
```

## Usage Examples

### Example 1: HTTP + gRPC Hybrid

```typescript
const transportConfig = {
  serviceName: 'user',
  transports: [
    createHttpConfig(configService), // REST API
    createGrpcConfig(configService, protoPath, 'user'), // High-performance RPC
  ],
};
```

### Example 2: All Transports

```typescript
const transportConfig = {
  serviceName: 'notification',
  transports: [
    createHttpConfig(configService),
    createGrpcConfig(configService, protoPath, 'notification'),
    createTcpConfig(configService),
    createRmqConfig(configService, 'notifications_queue'),
    createNatsConfig(configService),
  ],
};
```

### Example 3: Queue-Based Only

```typescript
const transportConfig = {
  serviceName: 'worker',
  transports: [
    createRmqConfig(configService, 'jobs_queue'),
  ],
};
```

## Transport Selection Guide

| Transport | Best For | Speed | Reliability |
|-----------|----------|-------|-------------|
| **HTTP** | External APIs, REST | Medium | Medium |
| **gRPC** | Internal high-performance | Fast | High |
| **TCP** | Custom protocols | Fast | Medium |
| **RabbitMQ** | Async jobs, queues | Slow | Very High |
| **NATS** | Real-time events | Very Fast | Medium |

## Service Discovery Integration

Works seamlessly with `@katdev/service-discovery`:

```typescript
const discoveryClient = app.get(ServiceDiscoveryClientImpl);

const { transports } = await configureApplication(
  app,
  transportConfig,
  discoveryClient
);

// Each transport automatically registers:
// - service-name:3003 (http)
// - service-name:5003 (grpc)
// - service-name:4003 (tcp)
```

## API Reference

### `createHttpConfig(configService, options?)`
Create HTTP transport configuration.

### `createGrpcConfig(configService, protoPath, package)`
Create gRPC transport configuration.

### `createTcpConfig(configService)`
Create TCP transport configuration.

### `createRmqConfig(configService, queueName)`
Create RabbitMQ transport configuration.

### `createNatsConfig(configService)`
Create NATS transport configuration.

### `configureApplication(app, config, discoveryClient)`
Configure all transports and register with service discovery.

### `startApplication(bootstrapResult)`
Start all configured transports.

## Environment Variables Reference

### HTTP
- `TRANSPORT_HTTP_ENABLED` - Enable HTTP transport (true/false)
- `HTTP_PORT` - HTTP server port (default: 3000)
- `HTTP_HOST` - HTTP host (default: 0.0.0.0)
- `HTTP_GLOBAL_PREFIX` - API prefix (e.g., 'api/v1')
- `CORS_ORIGIN` - CORS origin (default: *)
- `CORS_CREDENTIALS` - Allow credentials (true/false)

### gRPC
- `TRANSPORT_GRPC_ENABLED` - Enable gRPC transport (true/false)
- `GRPC_PORT` - gRPC server port (default: 5000)
- `GRPC_HOST` - gRPC host (default: 0.0.0.0)

### TCP
- `TRANSPORT_TCP_ENABLED` - Enable TCP transport (true/false)
- `TCP_PORT` - TCP server port (default: 4000)
- `TCP_HOST` - TCP host (default: 0.0.0.0)
- `TCP_RETRY_ATTEMPTS` - Retry attempts (default: 3)
- `TCP_RETRY_DELAY` - Retry delay in ms (default: 3000)

### RabbitMQ
- `TRANSPORT_RMQ_ENABLED` - Enable RabbitMQ transport (true/false)
- `RMQ_URLS` - RabbitMQ connection URL
- `RMQ_QUEUE` - Queue name
- `RMQ_DURABLE` - Durable queue (true/false)
- `RMQ_PREFETCH_COUNT` - Prefetch count (default: 10)

### NATS
- `TRANSPORT_NATS_ENABLED` - Enable NATS transport (true/false)
- `NATS_SERVERS` - NATS server URL
- `NATS_QUEUE` - Queue group name

## Troubleshooting

### Error: No driver (HTTP) has been selected

Install `@nestjs/platform-express`:
```bash
npm install @nestjs/platform-express
```

### Error: amqplib package is missing

Install RabbitMQ dependencies:
```bash
npm install amqplib amqp-connection-manager
```

### Error: nats package is missing

Install NATS dependency:
```bash
npm install nats
```

## License

MIT