NestJS course ยท Module 1: NestJS Basics
PROJECT: The Legion Register of the Empire
In this lesson8
Ave, legate! Throughout the module you built single pieces: a controller here, a service there, a DTO and the configuration separately. A real application is not a pile of loose blocks - it is one organism in which a request passes through several hands before the response comes back. Time to put everything together: the Legion Register, an API in which the Empire's chancellery receives, checks and stores legionaries' data.
What you will build
A REST API with five endpoints under the /legionaries address:
| Method | Address | What it does | Response code |
|---|---|---|---|
| GET | /legionaries | list of all legionaries | 200 |
| GET | /legionaries/search?province=Gallia | legionaries from one province | 200 |
| GET | /legionaries/:id | one legionary | 200 or 404 |
| POST | /legionaries | recruiting a new legionary | 201 or 400 |
| DELETE | /legionaries/:id | striking off the register | 204 or 404 |
You met every element of this table in this module. The project checks whether you can combine them into one application.
Stage 1: project and packages
Start with a new project (the nest new generator in NestJS 12 needs Node.js 22.22.3+ or 24.15+) and install the packages we used in the lessons on DTOs and configuration:
npm install -g @nestjs/cli
nest new legion-register
cd legion-register
npm i @nestjs/config joi class-validator class-transformer @nestjs/mapped-typesThen create a .env file in the project folder. Remember that it does not go into the repository - add it to .gitignore, and next to it save a .env.example with the same keys:
PORT=3000
LEGION_NAME=Legio X EquestrisStage 2: the DTO - a recruitment form
The register accepts only complete applications. Describe them with a DTO class with decorators from class-validator:
// legion/dto/create-legionary.dto.ts
import { IsEmail, IsIn, IsNotEmpty, IsString } from 'class-validator';
export class CreateLegionaryDto {
@IsString()
@IsNotEmpty()
name: string;
@IsIn(['Miles', 'Optio', 'Centurio'])
rank: string;
@IsString()
@IsNotEmpty()
province: string;
@IsEmail()
email: string;
}The decorators alone do not block anything yet. They start working together with ValidationPipe, which you will turn on in stage 5.
Stage 3: the service - the register's chancellery
All the logic lives in the service. It keeps legionaries in an array, gives them consecutive numbers and reports a missing legionary with the NotFoundException exception. It reads the legion's name from the configuration through ConfigService:
// legion/legion.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { CreateLegionaryDto } from './dto/create-legionary.dto';
export interface Legionary extends CreateLegionaryDto {
id: number;
}
@Injectable()
export class LegionService {
private legionaries: Legionary[] = [];
private nextId = 1;
constructor(private readonly configService: ConfigService) {}
findAll(): Legionary[] {
return this.legionaries;
}
findByProvince(province: string): Legionary[] {
return this.legionaries.filter((l) => l.province === province);
}
findOne(id: number): Legionary {
const legionary = this.legionaries.find((l) => l.id === id);
if (!legionary) {
throw new NotFoundException('No legionary with number ' + id);
}
return legionary;
}
recruit(data: CreateLegionaryDto): Legionary {
const legionary = { id: this.nextId++, ...data };
this.legionaries.push(legionary);
return legionary;
}
dismiss(id: number): void {
this.findOne(id);
this.legionaries = this.legionaries.filter((l) => l.id !== id);
}
getLegionName(): string {
return this.configService.get('LEGION_NAME');
}
}Note the nextId counter. A number taken from the array length would repeat after striking off someone from the middle of the register, while the counter always grows. The dismiss method calls findOne first, so removing a legionary who does not exist also ends with a 404 response.
Stage 4: the controller - a centurion at the gate
The controller only receives requests and passes them to the service. Watch the order of routes: search before :id, otherwise the /legionaries/search address would reach findOne:
// legion/legion.controller.ts
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Query } from '@nestjs/common';
import { CreateLegionaryDto } from './dto/create-legionary.dto';
import { LegionService } from './legion.service';
@Controller('legionaries')
export class LegionController {
constructor(private readonly legionService: LegionService) {}
@Get()
findAll() {
return this.legionService.findAll();
}
@Get('search')
search(@Query('province') province: string) {
return this.legionService.findByProvince(province);
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.legionService.findOne(Number(id));
}
@Post()
recruit(@Body() dto: CreateLegionaryDto) {
return this.legionService.recruit(dto);
}
@Delete(':id')
@HttpCode(HttpStatus.NO_CONTENT)
dismiss(@Param('id') id: string) {
this.legionService.dismiss(Number(id));
}
}The id from the address is text, so the controller turns it into a number with Number(id) before passing it to the service. You do not have to set the 201 code for @Post() - NestJS picks it itself.
Stage 5: modules and starting the application
The legion module registers the controller and the service:
// legion/legion.module.ts
import { Module } from '@nestjs/common';
import { LegionController } from './legion.controller';
import { LegionService } from './legion.service';
@Module({
controllers: [LegionController],
providers: [LegionService],
})
export class LegionModule {}The root module loads the configuration, checks it at startup with a Joi schema and adds the legion module:
// app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
import { LegionModule } from './legion/legion.module';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
validationSchema: Joi.object({
PORT: Joi.number().default(3000),
LEGION_NAME: Joi.string().required(),
}),
}),
LegionModule,
],
})
export class AppModule {}Finally, main.ts turns on validation for the whole application and starts the server:
// main.ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();Check the register
Start the server with npm run start:dev and test the endpoints in a second terminal:
curl -X POST http://localhost:3000/legionaries \
-H "Content-Type: application/json" \
-d '{"name": "Titus Pullo", "rank": "Miles", "province": "Gallia", "email": "titus@legio.rome"}'
curl "http://localhost:3000/legionaries/search?province=Gallia"
curl http://localhost:3000/legionaries/1
curl -X DELETE http://localhost:3000/legionaries/1
curl http://localhost:3000/legionaries/1The last command should return 404, because the legionary has been struck off. Also send an application with a wrong email address or a rank outside the list - ValidationPipe will answer with code 400 and a list of errors.
What you hand in
Push the project to GitHub and submit the link in the next task. In the README describe the endpoints and how to run the project: npm install, a .env file created from .env.example and npm run start:dev. For the eager: add PATCH /legionaries/:id with an UpdateLegionaryDto based on PartialType, as in the lesson on DTOs.
Remember, legate: in a well-built Empire everyone knows their place - the controller receives, the service executes, the DTO guards the gate, and the configuration lives outside the code.
Code for this lesson: src/imperium-project.ts
// PROJECT: Complex Imperium Romanum Application
import { Module, Controller, Injectable, Get, Post, Body, Param } from '@nestjs/common';
console.log("=== PROJECT: Imperium Management System ===");
// ===========================================
// 1. Legion Module
// ===========================================
interface Legion {
id: number;
name: string;
commander: string;
soldiers: number;
province: string;
}
@Injectable()
export class LegionService {
private legions: Legion[] = [
{ id: 1, name: 'Legio X Gemina', commander: 'Caesar', soldiers: 5000, province: 'Gallia' },
{ id: 2, name: 'Legio III Augusta', commander: 'Scipio', soldiers: 4500, province: 'Africa' },
];
findAll(): Legion[] { return this.legions; }
findById(id: number): Legion | undefined {
return this.legions.find(l => l.id === id);
}
create(data: Omit<Legion, 'id'>): Legion {
const legion = { id: this.legions.length + 1, ...data };
this.legions.push(legion);
return legion;
}
}
@Controller('legiones')
export class LegionController {
constructor(private legionService: LegionService) {}
@Get()
findAll() { return this.legionService.findAll(); }
@Get(':id')
findOne(@Param('id') id: string) { return this.legionService.findById(+id); }
}
@Module({
controllers: [LegionController],
providers: [LegionService],
exports: [LegionService],
})
export class LegionModule {}
// ===========================================
// 2. Tribute Module
// ===========================================
interface Tribute {
id: number;
province: string;
amount: number;
type: 'gold' | 'silver' | 'goods';
collectedAt: string;
}
@Injectable()
export class TributeService {
private tributes: Tribute[] = [
{ id: 1, province: 'Gallia', amount: 50000, type: 'gold', collectedAt: '44 BC' },
{ id: 2, province: 'Aegyptus', amount: 80000, type: 'gold', collectedAt: '30 BC' },
];
findAll() { return this.tributes; }
getTotal() { return this.tributes.reduce((sum, t) => sum + t.amount, 0); }
}
// ===========================================
// 3. Province Module
// ===========================================
@Injectable()
export class ProvinciaService {
private provinces = [
{ name: 'Gallia', governor: 'Gaius Julius Caesar', population: 120000 },
{ name: 'Aegyptus', governor: 'Gaius Cornelius Gallus', population: 300000 },
{ name: 'Britannia', governor: 'Aulus Plautius', population: 80000 },
];
findAll() { return this.provinces; }
}
// ===========================================
// Main application module
// ===========================================
@Module({
imports: [LegionModule],
providers: [TributeService, ProvinciaService],
})
export class AppModule {}
console.log("\n=== PROJECT STRUCTURE ===");
console.log("LegionModule - managing legions (Controller + Service)");
console.log("TributeService - managing tributes");
console.log("ProvinciaService - managing provinces");
console.log("AppModule - main module connecting everything");
console.log("\nThe project combines modules, dependency injection,");
console.log("controllers and services into one application.");
Docs entries used in this lesson
Spotted a mistake in this lesson?