NestJS course · Module 12: Containers and CI/CD
PROJECT: Comprehensive Roman Empire Application
In this lesson6
Ave, legate! Consul Caesar.js has entrusted you with the greatest challenge - creating a complete application for managing the Roman Empire. This will be a true test of all the skills you've acquired during your NestJS training!
Project Specification: Imperium Management System
Your application must be a complete Roman legion management system, handling:
1. User System and Authorization
- Legionary registration and login with different ranks
- JWT Authentication with refresh tokens
- Role-based access control (RBAC)
- Multi-factor authentication for consuls
2. Legion Management
- Legions - different types, capacities, equipment
- Soldiers - legionaries with skills and histories
- Campaigns - tribute expeditions with route planning
- Forts - operational bases with resources
3. Tribute System
- Inventory management - chests, tributes, artifacts
- Trading system - exchange between legions
- Auction house - bidding on rare items
- Value tracking - tracking value over time
4. Communication and Coordination
- Real-time messaging - WebSocket communication
- Legion announcements - announcements for legions
- Battle coordination - coordination during battles
- Weather alerts - weather notifications
5. Analytics and Reports
- Performance dashboards - legion statistics
- Tribute reports - profit analyses
- Legion analytics - legion efficiency
- Predictive insights - AI-driven predictions
Technical Structure
Core Modules
// app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { BullModule } from '@nestjs/bull';
import { CacheModule } from '@nestjs/cache-manager';
import { EventEmitterModule } from '@nestjs/event-emitter';
// Custom modules
import { AuthModule } from './auth/auth.module';
import { LegionModule } from './legion/legion.module';
import { LegionaryModule } from './legionary/legionary.module';
import { TributeModule } from './tribute/tribute.module';
import { CampaignModule } from './campaign/campaign.module';
import { CommunicationModule } from './communication/communication.module';
import { AnalyticsModule } from './analytics/analytics.module';
import { WebsocketModule } from './websocket/websocket.module';
// Configuration
import { databaseConfig, redisConfig, appConfig } from './config';
import { validationSchema } from './config/validation.schema';
@Module({
imports: [
// Configuration
ConfigModule.forRoot({
isGlobal: true,
load: [databaseConfig, redisConfig, appConfig],
validationSchema,
}),
// Database
TypeOrmModule.forRootAsync({
useFactory: (configService: ConfigService) => configService.get('database'),
inject: [ConfigService],
}),
// GraphQL
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: 'schema.gql',
subscriptions: {
'graphql-ws': true,
},
context: ({ req, connection }) =>
connection ? { req: connection.context } : { req },
}),
// Redis & Caching
BullModule.forRootAsync({
useFactory: (configService: ConfigService) => configService.get('redis'),
inject: [ConfigService],
}),
CacheModule.registerAsync({
useFactory: (configService: ConfigService) => ({
store: 'redis',
...configService.get('redis'),
ttl: 300, // 5 minutes default
}),
inject: [ConfigService],
}),
// Event system
EventEmitterModule.forRoot(),
// Feature modules
AuthModule,
LegionModule,
LegionaryModule,
TributeModule,
CampaignModule,
CommunicationModule,
AnalyticsModule,
WebsocketModule,
],
providers: [
// Global guards
{
provide: APP_GUARD,
useClass: JwtAuthGuard,
},
{
provide: APP_GUARD,
useClass: RolesGuard,
},
// Global interceptors
{
provide: APP_INTERCEPTOR,
useClass: LoggingInterceptor,
},
{
provide: APP_INTERCEPTOR,
useClass: TransformInterceptor,
},
// Global filters
{
provide: APP_FILTER,
useClass: AllExceptionsFilter,
},
],
})
export class AppModule {}Advanced Features Implementation
// auth/strategies/jwt.strategy.ts
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private configService: ConfigService,
private userService: UserService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.get<string>('jwt.secret'),
});
}
async validate(payload: any) {
const user = await this.userService.findById(payload.sub);
if (!user || !user.isActive) {
throw new UnauthorizedException('Legionary not found or inactive');
}
return user;
}
}
// websocket/legion-communication.gateway.ts
@WebSocketGateway({
cors: {
origin: '*',
},
})
export class LegionCommunicationGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer()
server: Server;
private logger: Logger = new Logger('LegionCommunicationGateway');
private legionaryConnections = new Map<string, string>(); // socketId -> legionaryId
afterInit(server: Server) {
this.logger.log('Legion Communication Gateway initialized');
}
async handleConnection(client: Socket, ...args: any[]) {
try {
const token = client.handshake.auth.token;
const legionary = await this.authService.validateToken(token);
this.legionaryConnections.set(client.id, legionary.id);
client.join(`cohort_${legionary.cohortId}`);
client.join(`legion_${legionary.legionId}`);
this.server.to(`cohort_${legionary.cohortId}`).emit('legionaryJoined', {
legionary: legionary.name,
message: `${legionary.name} joined the communication channel`,
});
this.logger.log(`Legionary ${legionary.name} connected to legion communication`);
} catch (error) {
this.logger.error('Connection failed:', error);
client.disconnect();
}
}
handleDisconnect(client: Socket) {
const legionaryId = this.legionaryConnections.get(client.id);
if (legionaryId) {
this.legionaryConnections.delete(client.id);
this.logger.log(`Legionary ${legionaryId} disconnected`);
}
}
@SubscribeMessage('cohortMessage')
handleCohortMessage(client: Socket, payload: any) {
const legionaryId = this.legionaryConnections.get(client.id);
const legionary = this.userService.findById(legionaryId);
client.to(`cohort_${legionary.cohortId}`).emit('cohortMessage', {
from: legionary.name,
message: payload.message,
timestamp: new Date(),
});
}
@SubscribeMessage('legionAnnouncement')
@UseGuards(WsJwtGuard, WsRolesGuard)
@Roles('CENTURION', 'CONSUL')
handleLegionAnnouncement(client: Socket, payload: any) {
const legionaryId = this.legionaryConnections.get(client.id);
const legionary = this.userService.findById(legionaryId);
this.server.to(`legion_${legionary.legionId}`).emit('legionAnnouncement', {
from: legionary.name,
rank: legionary.rank,
message: payload.message,
priority: payload.priority || 'normal',
timestamp: new Date(),
});
}
}
// analytics/services/advanced-analytics.service.ts
@Injectable()
export class AdvancedAnalyticsService {
constructor(
private dataSource: DataSource,
@InjectQueue('analytics') private analyticsQueue: Queue,
) {}
async generateLegionPerformanceReport(legionId: number, period: string) {
const job = await this.analyticsQueue.add('legion-performance', {
legionId,
period,
});
return { jobId: job.id };
}
async getPredictiveTributeInsights(legionId: number) {
// Machine learning predictions (TensorFlow.js example)
const historicalData = await this.getHistoricalTributeData(legionId);
const predictions = await this.mlPredict(historicalData);
return {
predictedTributeValue: predictions.value,
confidence: predictions.confidence,
recommendedActions: predictions.actions,
timeframe: '30 days',
};
}
private async mlPredict(data: any[]) {
// Simple ML model example
const values = data.map(d => d.value);
const trend = this.calculateTrend(values);
const seasonality = this.calculateSeasonality(data);
return {
value: trend.nextPrediction * seasonality.factor,
confidence: Math.min(trend.confidence * seasonality.confidence, 0.95),
actions: this.generateRecommendations(trend, seasonality),
};
}
@Cron('0 2 * * *') // Daily at 2:00 AM
async generateDailyReports() {
const legions = await this.getActiveLegions();
for (const legion of legions) {
await this.analyticsQueue.add('daily-report', {
legionId: legion.id,
date: new Date(),
});
}
}
}
// tribute/services/auction.service.ts
@Injectable()
export class AuctionService {
constructor(
private auctionRepository: AuctionRepository,
private eventEmitter: EventEmitter2,
@InjectQueue('auction') private auctionQueue: Queue,
) {}
async createAuction(tributeId: number, sellerId: number, startingPrice: number, duration: number) {
const auction = await this.auctionRepository.create({
tributeId,
sellerId,
startingPrice,
currentPrice: startingPrice,
endTime: new Date(Date.now() + duration * 1000),
status: 'ACTIVE',
});
// Schedule auction end
await this.auctionQueue.add(
'end-auction',
{ auctionId: auction.id },
{ delay: duration * 1000 }
);
this.eventEmitter.emit('auction.created', auction);
return auction;
}
async placeBid(auctionId: number, bidderId: number, amount: number) {
const auction = await this.auctionRepository.findById(auctionId);
if (auction.status !== 'ACTIVE' || new Date() > auction.endTime) {
throw new BadRequestException('Auction is not active');
}
if (amount <= auction.currentPrice) {
throw new BadRequestException('Bid must be higher than current price');
}
// Anti-sniping: extend auction if bid in last 5 minutes
const timeLeft = auction.endTime.getTime() - Date.now();
if (timeLeft < 5 * 60 * 1000) {
auction.endTime = new Date(auction.endTime.getTime() + 5 * 60 * 1000);
}
auction.currentPrice = amount;
auction.currentBidderId = bidderId;
await this.auctionRepository.save(auction);
this.eventEmitter.emit('auction.bid', {
auctionId,
bidderId,
amount,
timeLeft: Math.max(0, timeLeft),
});
return auction;
}
@OnEvent('auction.end')
async handleAuctionEnd(auctionId: number) {
const auction = await this.auctionRepository.findById(auctionId);
if (auction.currentBidderId) {
await this.transferTribute(auction.tributeId, auction.currentBidderId);
await this.transferFunds(auction.currentBidderId, auction.sellerId, auction.currentPrice);
auction.status = 'COMPLETED';
auction.winnerId = auction.currentBidderId;
} else {
auction.status = 'NO_BIDS';
}
await this.auctionRepository.save(auction);
this.eventEmitter.emit('auction.completed', auction);
}
}Tasks to complete
Stage 1: Basic architecture (Week 1)
- Project setup - NestJS, TypeORM, Redis configuration
- Authentication system - JWT, refresh tokens, role-based access
- Base entities - User, Legion, Cohort, Tribute basics
- API endpoints - CRUD operations for basic entities
- Basic tests - unit tests for services
Stage 2: Business functionalities (Week 2)
- Campaign system - planning and executing campaigns
- Trading system - tribute exchange between legionaries
- Legion management - managing legions and skills
- Notification system - real-time notifications
- Advanced validation - complex business rules
Stage 3: Real-time and advanced (Week 3)
- WebSocket integration - real-time communication
- Auction system - tribute auctions
- Analytics dashboard - statistics and metrics
- Background jobs - async task processing
- Performance optimization - caching, indexes, optimizations
Stage 4: Production and advanced (Week 4)
- GraphQL implementation - alternative API
- Rate limiting - protection against spam
- Monitoring - health checks, metrics, alerting
- Deployment - Docker, CI/CD, environment management
- Advanced security - security headers, CORS, data encryption
Evaluation criteria
Functionality (25%)
- All required features work correctly
- Comprehensive authorization and permissions system
- Real-time communication between users
- Advanced business features (auctions, missions, trading)
Code quality (25%)
- Readable architecture and project structure
- Proper use of design patterns
- Consistent code style and naming conventions
- Proper error handling and validation
Performance and scalability (20%)
- Database query optimization
- Effective caching strategies
- Background job processing
- Rate limiting and resource management
Tests (15%)
- Comprehensive unit tests (>80% coverage)
- Integration tests for key flows
- E2E tests for main functionalities
- Performance tests
Documentation (15%)
- API documentation (Swagger/OpenAPI)
- README with setup and deployment instructions
- Architecture documentation
- Code comments where needed
Bonus Points
- GraphQL subscriptions for real-time updates
- Machine learning predictions for tribute values
- Microservices architecture with message queues
- Advanced monitoring with Prometheus/Grafana
- Mobile app communicating with the API
Example API endpoints
// Legion Management
GET /api/legions # List legions
POST /api/legions # Create legion
GET /api/legions/:id # Legion details
PUT /api/legions/:id # Update legion
DELETE /api/legions/:id # Delete legion
// Cohort Management
GET /api/cohorts # List cohorts
POST /api/cohorts # Add cohort
GET /api/cohorts/:id # Cohort details
PUT /api/cohorts/:id # Update cohort
POST /api/cohorts/:id/assign-legionaries # Assign legionaries
POST /api/cohorts/:id/campaigns # Create campaign
// Tribute System
GET /api/tributes # List tributes
POST /api/tributes # Add tribute
GET /api/tributes/:id # Tribute details
PUT /api/tributes/:id/transfer # Transfer tribute
POST /api/tributes/:id/auction # List for auction
// Auctions
GET /api/auctions # Active auctions
POST /api/auctions/:id/bid # Place a bid
GET /api/auctions/:id/history # Bidding history
// Analytics
GET /api/analytics/legion/:id # Legion statistics
GET /api/analytics/tribute-trends # Tribute value trends
GET /api/analytics/legion-performance # Legion performance
// Real-time WebSocket events
cohort:message # Messages in cohort
legion:announcement # Legion announcements
auction:bid # New auction bid
campaign:update # Campaign update
tribute:discovered # Tribute discoveredThis is the greatest challenge in the service of the Roman Empire! Good luck, legate - the Empire is counting on you!
Docs entries used in this lesson
Spotted a mistake in this lesson?