@abdullahbakouni/nestjs-microservices-generator
v1.0.1
Published
Interactive CLI to generate NestJS microservices monorepo with Kafka & Redis
Maintainers
Readme
🚀 NestJS Microservices Generator
Interactive CLI tool to generate a complete NestJS microservices monorepo with Kafka, Redis, and more in seconds!
✨ Features
- 🎯 Interactive CLI - Guided setup with beautiful prompts
- 🏗️ NestJS Monorepo - Single package.json for all microservices
- 📦 Shared Libraries - Pre-configured
@app/commonwith Kafka & Redis modules - ⚡ Kafka Integration - Full Kafka module with producer/consumer support
- 🔴 Redis Integration - Complete Redis service with all operations (cache, pub/sub, lists, sets, etc.)
- 🐳 Docker Compose - Ready-to-use Docker setup with Kafka, Zookeeper, and Redis
- 🔧 TypeScript - Fully typed with best practices
- 🎨 Customizable - Choose only the features you need
- 📝 Auto-generated - Creates controllers, services, and modules automatically
📦 Installation
Global Installation (Recommended)
npm install -g @abdullahbakouni/nestjs-microservices-generatorOr use with npx (No installation needed)
npx @abdullahbakouni/nestjs-microservices-generator🎬 Quick Start
# Run the generator
create-nest-microservices
# Or with npx
npx @abdullahbakouni/nestjs-microservices-generatorFollow the interactive prompts:
🚀 NestJS Microservices Generator
? What is your project name? my-ecommerce
? How many microservices do you want to create? 3
? Name for microservice #1: api-gateway
? Name for microservice #2: user-service
? Name for microservice #3: order-service
? Select features to include:
◉ Kafka integration
◉ Redis integration
◉ Docker Compose
◯ TypeORM Database
◯ JWT Authentication
? Kafka broker address: localhost:9092
? Redis host: localhost
? Redis port: 6379
✅ Project generated successfully!🏗️ Generated Project Structure
my-ecommerce/
├── package.json # Single package.json for all services
├── nest-cli.json # Monorepo configuration
├── tsconfig.json
├── docker-compose.yml # Kafka, Redis, and services
├── apps/
│ ├── api-gateway/
│ │ └── src/
│ │ ├── main.ts # HTTP + Kafka bootstrap
│ │ ├── api-gateway.module.ts
│ │ ├── api-gateway.controller.ts
│ │ └── api-gateway.service.ts
│ ├── user-service/
│ └── order-service/
└── libs/
└── common/
└── src/
├── index.ts
├── kafka/
│ ├── kafka.module.ts # forRoot, forRootAsync, forProducer, forConsumer
│ ├── kafka.service.ts # emit, send, consume, subscribe
│ └── events/
│ └── topics.ts # Predefined Kafka topics
├── redis/
│ ├── redis.module.ts # forRoot, forRootAsync
│ └── redis.service.ts # Full Redis operations
└── interfaces/
└── index.ts🚀 Usage
Install Dependencies
cd my-ecommerce
npm installStart All Services
# Start with Docker Compose (includes Kafka & Redis)
docker-compose up -d
# Start a specific service in development mode
npm run start:api-gateway
npm run start:user-service
npm run start:order-serviceAvailable Scripts
npm run build # Build all services
npm run build:all # Build all services explicitly
npm run start # Start default service
npm run start:dev # Start in watch mode
npm run start:api-gateway # Start specific service
npm run start:user-service
npm run start:order-service📚 Using Shared Libraries
Kafka Module
The generated Kafka module supports multiple patterns:
1. Basic Usage (forRoot)
import { Module } from '@nestjs/common';
import { KafkaModule } from '@app/common';
@Module({
imports: [
KafkaModule.forRoot({
clientId: 'user-service',
brokers: ['localhost:9092'],
groupId: 'user-service-group',
}),
],
})
export class UserModule {}2. Async Configuration (forRootAsync)
import { ConfigModule, ConfigService } from '@nestjs/config';
import { KafkaModule } from '@app/common';
@Module({
imports: [
KafkaModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
clientId: config.get('KAFKA_CLIENT_ID'),
brokers: [config.get('KAFKA_BROKER')],
groupId: config.get('KAFKA_GROUP_ID'),
}),
}),
],
})
export class UserModule {}3. Producer Only (forProducer)
KafkaModule.forProducer({
clientId: 'notification-producer',
brokers: ['localhost:9092'],
})4. Consumer Only (forConsumer)
KafkaModule.forConsumer({
clientId: 'order-consumer',
brokers: ['localhost:9092'],
groupId: 'order-service-group',
})Kafka Service Usage
import { Injectable } from '@nestjs/common';
import { KafkaService, KAFKA_TOPICS } from '@app/common';
@Injectable()
export class UserService {
constructor(private readonly kafkaService: KafkaService) {}
async createUser(userData: any) {
// Emit event (fire and forget)
this.kafkaService.emit(KAFKA_TOPICS.USER_CREATED, {
userId: userData.id,
email: userData.email,
});
// Send and wait for response
const result = await this.kafkaService.send(
KAFKA_TOPICS.NOTIFICATION_SEND,
{ type: 'welcome', userId: userData.id }
);
return result;
}
}Listen to Events with @EventPattern
import { Controller } from '@nestjs/common';
import { EventPattern, Payload } from '@nestjs/microservices';
import { KAFKA_TOPICS } from '@app/common';
@Controller()
export class UserController {
@EventPattern(KAFKA_TOPICS.USER_CREATED)
async handleUserCreated(@Payload() data: any) {
console.log('User created:', data);
// Process the event
}
}Redis Module
Basic Usage
import { RedisModule } from '@app/common';
@Module({
imports: [
RedisModule.forRoot({
host: 'localhost',
port: 6379,
password: 'your-password', // optional
db: 0,
keyPrefix: 'myapp:',
}),
],
})
export class AppModule {}Async Configuration
RedisModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
host: config.get('REDIS_HOST'),
port: config.get('REDIS_PORT'),
password: config.get('REDIS_PASSWORD'),
}),
})Redis Service Usage
import { Injectable } from '@nestjs/common';
import { RedisService } from '@app/common';
@Injectable()
export class CacheService {
constructor(private readonly redis: RedisService) {}
// Basic operations
async cacheUser(userId: string, userData: any) {
await this.redis.set(`user:${userId}`, userData, 3600); // TTL 1 hour
}
async getUser(userId: string) {
return await this.redis.get(`user:${userId}`);
}
// Hash operations
async saveUserProfile(userId: string, profile: any) {
await this.redis.hset(`profile:${userId}`, 'name', profile.name);
await this.redis.hset(`profile:${userId}`, 'email', profile.email);
}
async getUserProfile(userId: string) {
return await this.redis.hgetall(`profile:${userId}`);
}
// List operations
async addToQueue(task: any) {
await this.redis.rpush('task-queue', task);
}
async getNextTask() {
return await this.redis.lpop('task-queue');
}
// Pub/Sub
async publishNotification(message: any) {
await this.redis.publish('notifications', message);
}
async subscribeToNotifications() {
await this.redis.subscribe('notifications', (message) => {
console.log('Received:', message);
});
}
// Sorted Sets (leaderboards)
async addScore(userId: string, score: number) {
await this.redis.zadd('leaderboard', score, { userId, score });
}
async getTopPlayers(limit: number) {
return await this.redis.zrange('leaderboard', 0, limit - 1);
}
}🐳 Docker Compose
The generated docker-compose.yml includes:
- Zookeeper - Kafka dependency
- Kafka - Message broker on port 9092
- Redis - Cache & pub/sub on port 6379
- All your microservices - Auto-configured and networked
# Start everything
docker-compose up -d
# View logs
docker-compose logs -f
# Stop everything
docker-compose down🎯 Kafka Topics
Pre-configured topics in libs/common/src/kafka/events/topics.ts:
export const KAFKA_TOPICS = {
// User Events
USER_CREATED: 'user.created',
USER_UPDATED: 'user.updated',
USER_DELETED: 'user.deleted',
// Order Events
ORDER_CREATED: 'order.created',
ORDER_COMPLETED: 'order.completed',
ORDER_CANCELLED: 'order.cancelled',
// Notification Events
NOTIFICATION_SEND: 'notification.send',
EMAIL_SEND: 'email.send',
SMS_SEND: 'sms.send',
};Add your own topics easily!
⚙️ Configuration
Each microservice has its own .env.example:
API_GATEWAY_PORT=3000
KAFKA_BROKER=localhost:9092
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=🔧 Customization
Add a New Microservice
# Use NestJS CLI
nest generate app payment-serviceThe service will be automatically added to nest-cli.json!
Add Custom Kafka Topics
Edit libs/common/src/kafka/events/topics.ts:
export const KAFKA_TOPICS = {
// Your custom topics
PAYMENT_PROCESSED: 'payment.processed',
INVOICE_GENERATED: 'invoice.generated',
} as const;📖 API Reference
KafkaService Methods
| Method | Description |
|--------|-------------|
| emit(topic, data) | Fire and forget event |
| send(topic, data) | Send and wait for response |
| subscribeToTopic(topic) | Subscribe to a topic |
| consume(options) | Set up consumer with callback |
RedisService Methods
| Category | Methods |
|----------|---------|
| Basic | get, set, del, exists, expire, ttl |
| Hash | hset, hget, hgetall, hdel |
| List | lpush, rpush, lpop, lrange |
| Set | sadd, smembers, sismember, srem |
| Sorted Set | zadd, zrange, zrangebyscore |
| Pub/Sub | publish, subscribe, unsubscribe |
| Counter | incr, decr, incrby |
| Pattern | keys, deletePattern |
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📝 License
MIT © Abdullah Bakouni
🐛 Issues
Found a bug? Open an issue
⭐ Show Your Support
Give a ⭐️ if this project helped you!
📧 Contact
- GitHub: @abdullahbakouni
- Email: [email protected]
Made with ❤️ by Abdullah Bakouni
