NestJS course Β· Module 1: NestJS Basics

Welcome to the Empire! Introduction to NestJS

5 min read Β·
In this lesson8

Salve, young legionary! Welcome to the Roman technology system! I am Consul Caesar.js, and you will become my young legionary in a campaign through the vast provinces of NestJS - the most powerful Node.js framework in the Internet Empire!

Just as the Roman Empire needs solid construction, an experienced legion, and well-organized cohorts, a NestJS application requires well-thought-out architecture, modularity, and a professional approach to building scalable server-side applications.

What is NestJS?

NestJS is a progressive Node.js framework for building efficient and scalable server-side applications. It was built in TypeScript and leverages the best patterns from the JavaScript ecosystem, combining them with powerful decorators and a dependency injection system known from Angular.

Imagine that NestJS is our mighty Roman Empire:

// Our Roman cohorts (modules)
import { Module } from '@nestjs/common';
import { LegionModule } from './legion/legion.module';
import { TributesModule } from './tributes/tributes.module';
import { ForumModule } from './forum/forum.module';

@Module({
  imports: [LegionModule, TributesModule, ForumModule],
})
export class ImperiumModule {}

Fundamentals of NestJS

1. Decorators - our Roman rank insignia

In NestJS, decorators are like Roman rank insignia - they mark the rank and function of each element of the legion:

// The Consul controls the entire operation
@Controller('consul')
export class ConsulController {
  // Handles orders regarding tributes
  @Get('tributes')
  findTributes() {
    return 'Imperial tributes from all provinces!';
  }

  // Recruits new legionaries
  @Post('legion')
  recruitLegionary(@Body() newLegionary: CreateLegionaryDto) {
    return 'New legionary recruited successfully!';
  }
}

2. Modules - structures of our Empire

Each module is a separate structure of the Empire with a specific purpose:

// Structure responsible for the legion
@Module({
  controllers: [LegionController],
  providers: [LegionService],
  exports: [LegionService],
})
export class LegionModule {}

// Structure responsible for tributes
@Module({
  controllers: [TributesController],
  providers: [TributesService],
  imports: [DatabaseModule],
})
export class TributesModule {}

3. Dependency Injection - the chain of command

The DI system in NestJS is like the hierarchy in a Roman legion - everyone knows who to take orders from:

@Injectable()
export class TributesService {
  constructor(
    private readonly mapService: MapService,
    private readonly collectorService: CollectorService,
  ) {}

  async findTributes(province: string) {
    const location = await this.mapService.getProvince(province);
    return this.collectorService.collect(location);
  }
}

Installation and first steps

To begin our campaign in the Empire, you need the proper equipment. The base is Node.js: the nest new project generator in NestJS 12 requires version 22.22.3 or later on the 22 line, or 24.15 or later. You can check it with node -v. Then four commands are enough:

# Install NestJS CLI - our engineering tools
npm install -g @nestjs/cli

# Create a new Empire (project)
nest new roman-imperium

# Enter the system
cd roman-imperium

# Raise the legion standards (start the server)
npm run start:dev

Structure of the Roman Empire (project)

roman-imperium/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main.ts               # Forum Romanum - entry point
β”‚   β”œβ”€β”€ app.module.ts         # The Main Senate
β”‚   β”œβ”€β”€ app.controller.ts     # Consul - main controller
β”‚   β”œβ”€β”€ app.service.ts        # Primus Centurion
β”‚   β”œβ”€β”€ legion/               # Legion structure
β”‚   β”‚   β”œβ”€β”€ legion.module.ts
β”‚   β”‚   β”œβ”€β”€ legion.controller.ts
β”‚   β”‚   └── legion.service.ts
β”‚   β”œβ”€β”€ tributes/             # Tributes structure
β”‚   └── forum/                # Forum structure
β”œβ”€β”€ test/                     # Training grounds
β”œβ”€β”€ package.json              # Imperial registry
└── nest-cli.json             # Engineering instructions

First endpoint - imperial signal

Let's create our first endpoint that will signal the presence of the Empire:

// app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getSignal(): string {
    return 'Roman Imperium is ready for campaign!';
  }

  @Get('status')
  getImperiumStatus() {
    return {
      legion: 'Ready for campaign',
      tributes: 'Collecting...',
      destination: 'New provinces',
      consul: 'Caesar.js at your service!',
    };
  }
}

Advantages of NestJS for the Empire

  1. Modularity - each structure of the Empire has its own task
  2. TypeScript - precision like Roman engineering
  3. Decorators - readable markings like legion signals
  4. Testing - we check everything before setting out on a campaign
  5. Documentation - automatic maps of our provinces (Swagger)
  6. Scalability - from a small castrum to Empire architecture

Practical exercise

Time for the first imperial test! Create a simple controller that will manage basic information about the legion:

// legion.controller.ts
import { Controller, Get, Post, Body } from '@nestjs/common';

@Controller('legion')
export class LegionController {
  private legionaries = [
    { name: 'Marcus Aurelius', role: 'Centurion', experience: 10 },
    { name: 'Julius Brutus', role: 'Engineer', experience: 5 },
  ];

  @Get()
  getAllLegionaries() {
    return this.legionaries;
  }

  @Post()
  addLegionary(@Body() newLegionary: any) {
    this.legionaries.push(newLegionary);
    return { message: 'New legionary joined the legion!', legionary: newLegionary };
  }
}

Upcoming campaigns

In the following modules we will learn about:

  • Services and Providers - specialist roles in the Empire
  • Middleware - defense systems
  • Guards - Praetorian guards
  • Interceptors - signal interception
  • Pipes - data processing
  • Database integration - tribute warehouses
  • Authentication - identification of Empire citizens
  • WebSockets - communication between provinces
  • Testing - preparations before a campaign

Get ready, young legionary! An exciting campaign through the provinces of modern web development awaits us. NestJS is not just a framework - it's a powerful tool for building enterprise-class applications that will help you collect the most valuable tributes in the world of programming!

Remember: a true legionary-programmer never sets out without a map (documentation) and a compass (best practices)!

Code for this lesson: src/app.controller.ts
// NestJS Imperium Romanum - First Project
import { Controller, Get, Post, Body } from '@nestjs/common';
import { AppService } from './app.service';

console.log("Salve! Welcome to Imperium Romanum NestJS!");
console.log("Learning the basics of a framework for true empire builders\n");

// ===========================================
// 1. Basic controller - Emperor of the system
// ===========================================
console.log("=== 1. BASIC CONTROLLER ===");

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getWelcome(): string {
    return this.appService.getWelcome();
  }

  @Get('status')
  getImperiumStatus() {
    return {
      imperium: 'Roma Aeterna NestJS',
      caesar: 'Augustus.js',
      legiones: 'Ready for coding!',
      status: 'We build roads through TypeScript',
      framework: 'NestJS',
      timestamp: new Date().toISOString(),
    };
  }
}

// ===========================================
// 2. Legion Controller - Soldier Management
// ===========================================
console.log("=== 2. LEGION CONTROLLER ===");

interface Legionary {
  id: number;
  name: string;
  rank: string;
  experience: number;
  legio: string;
}

@Controller('legiones')
export class LegionController {
  private legionaries: Legionary[] = [
    {
      id: 1,
      name: 'Marcus Aurelius',
      rank: 'Legatus',
      experience: 10,
      legio: 'Legio X Gemina'
    },
    {
      id: 2,
      name: 'Gaius Julius',
      rank: 'Centurio',
      experience: 8,
      legio: 'Legio III Augusta'
    },
    {
      id: 3,
      name: 'Lucius Scipio',
      rank: 'Optio',
      experience: 6,
      legio: 'Legio IX Hispana'
    },
    {
      id: 4,
      name: 'Titus Flavius',
      rank: 'Miles',
      experience: 5,
      legio: 'Legio XII Fulminata'
    }
  ];

  @Get()
  getAllLegionaries(): Legionary[] {
    console.log("List of all legionaries");
    return this.legionaries;
  }

  @Get('commanders')
  getCommanders(): Legionary[] {
    console.log("List of commanders");
    return this.legionaries.filter(l => l.rank === 'Legatus' || l.rank === 'Centurio');
  }

  @Post()
  recruitLegionary(@Body() newLegionary: Omit<Legionary, 'id'>): Legionary {
    const legionary: Legionary = {
      id: this.getNextId(),
      ...newLegionary,
    };

    this.legionaries.push(legionary);
    console.log(`New legionary: ${legionary.name} as ${legionary.rank}`);

    return legionary;
  }

  @Get('stats')
  getLegionStats() {
    const totalExperience = this.legionaries.reduce((sum, l) => sum + l.experience, 0);
    const avgExperience = totalExperience / this.legionaries.length;

    const rankCounts = this.legionaries.reduce((counts, l) => {
      counts[l.rank] = (counts[l.rank] || 0) + 1;
      return counts;
    }, {} as Record<string, number>);

    return {
      totalMilites: this.legionaries.length,
      totalExperience,
      averageExperience: Math.round(avgExperience * 10) / 10,
      rankDistribution: rankCounts,
      mostExperienced: this.legionaries.reduce((prev, current) =>
        prev.experience > current.experience ? prev : current
      ),
    };
  }

  private getNextId(): number {
    return Math.max(...this.legionaries.map(l => l.id), 0) + 1;
  }
}

// ===========================================
// 3. Tributum Controller - Tax Management
// ===========================================
console.log("=== 3. TRIBUTUM CONTROLLER ===");

interface Tributum {
  id: number;
  name: string;
  value: number;
  provincia: string;
  collected: boolean;
  collectedBy?: string;
}

@Controller('tributum')
export class TributumController {
  private tributes: Tributum[] = [
    {
      id: 1,
      name: 'Aurum Galliae',
      value: 50000,
      provincia: 'Gallia',
      collected: true,
      collectedBy: 'Marcus Aurelius'
    },
    {
      id: 2,
      name: 'Argentum Hispaniae',
      value: 75000,
      provincia: 'Hispania',
      collected: false
    },
    {
      id: 3,
      name: 'Aes Britanniae',
      value: 100000,
      provincia: 'Britannia',
      collected: true,
      collectedBy: 'Gaius Julius'
    },
    {
      id: 4,
      name: 'Triticum Aegypti',
      value: 25000,
      provincia: 'Aegyptus',
      collected: false
    }
  ];

  @Get()
  getAllTributes(): Tributum[] {
    console.log("List of all taxes");
    return this.tributes;
  }

  @Get('collected')
  getCollectedTributes(): Tributum[] {
    console.log("Collected taxes");
    return this.tributes.filter(t => t.collected);
  }

  @Get('pending')
  getPendingTributes(): Tributum[] {
    console.log("Pending taxes");
    return this.tributes.filter(t => !t.collected);
  }

  @Post('collect/:id')
  collectTribute(@Body() collector: { collectedBy: string }) {
    const tributeId = 2;
    const tribute = this.tributes.find(t => t.id === tributeId);

    if (!tribute) {
      return { success: false, message: 'Tributum non inventum!' };
    }

    if (tribute.collected) {
      return { success: false, message: 'Tributum iam collectum!' };
    }

    tribute.collected = true;
    tribute.collectedBy = collector.collectedBy;

    console.log(`Tax collected: ${tribute.name} by ${collector.collectedBy}`);

    return {
      success: true,
      message: `Congratulations! ${collector.collectedBy} collected ${tribute.name}!`,
      tribute,
      reward: tribute.value
    };
  }

  @Get('aerarium')
  getAerarium() {
    const collectedValue = this.tributes
      .filter(t => t.collected)
      .reduce((sum, t) => sum + t.value, 0);

    const pendingValue = this.tributes
      .filter(t => !t.collected)
      .reduce((sum, t) => sum + t.value, 0);

    return {
      aerariumValue: collectedValue,
      pendingValue,
      totalValue: collectedValue + pendingValue,
      collectionPercentage: Math.round((collectedValue / (collectedValue + pendingValue)) * 100)
    };
  }
}

// ===========================================
// 4. API calls demonstration
// ===========================================
console.log("=== 4. API DEMONSTRATION ===");

class APIDemo {
  static async demonstrateAPICalls() {
    console.log("API call demonstration:");

    console.log("GET /legiones - Fetch legionaries:");
    const legionaries = new LegionController().getAllLegionaries();
    console.log(`Found ${legionaries.length} legionaries`);

    console.log("\nGET /legiones/stats - Legion statistics:");
    const stats = new LegionController().getLegionStats();
    console.log(`Total milites: ${stats.totalMilites}, Avg. experience: ${stats.averageExperience}`);

    console.log("\nGET /tributum - Fetch taxes:");
    const tributes = new TributumController().getAllTributes();
    console.log(`Found ${tributes.length} taxes`);

    console.log("\nGET /tributum/aerarium - Treasury status:");
    const aerarium = new TributumController().getAerarium();
    console.log(`Aerarium value: ${aerarium.aerariumValue} denarii (${aerarium.collectionPercentage}% collected)`);

    return {
      legionaries: legionaries.length,
      tributes: tributes.length,
      aerariumValue: aerarium.aerariumValue
    };
  }
}

// ===========================================
// 5. Demonstration start
// ===========================================
console.log("=== 5. APPLICATION STARTUP ===");

async function runImperiumDemo() {
  try {
    console.log("Starting Imperium Romanum NestJS Demo...");

    const results = await APIDemo.demonstrateAPICalls();

    console.log("\nIMPERIUM SUMMARY:");
    console.log(`Legionaries: ${results.legionaries} milites`);
    console.log(`Taxes: ${results.tributes} tributum`);
    console.log(`Aerarium: ${results.aerariumValue} denarii`);
    console.log("\nNestJS application ready for conquest!");

    return results;
  } catch (error) {
    console.error("Error in Imperium:", error);
    throw error;
  }
}

runImperiumDemo().then(() => {
  console.log("\nAve Caesar! Demo completed successfully!");
  console.log("Congratulations - you have mastered the basics of NestJS!");
});

export { AppController, LegionController, TributumController };

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is NestJS?

  2. 2. What programming language is NestJS built with?

Hands-on tasks in the game

  • Code editor

    Write a StatusController class with the @Controller('status') decorator and a getStatus() method with the @Get() decorator. The method must return an object with a status field, e.g. { status: 'The Empire is ready for the campaign' }.

  • Click in order

    Arrange the steps for creating a new NestJS project in the correct order:

  1. QuestionWhat is NestJS
  2. QuestionNestJS Programming Language
  3. Coding taskFirst NestJS Controller
  4. Click in orderCreating a NestJS Project

Useful articles