Skip to content

Latest commit

 

History

History
242 lines (181 loc) · 10.8 KB

File metadata and controls

242 lines (181 loc) · 10.8 KB

Nest.js Full Course for Beginners | Complete All-in-One Tutorial

Disclaimer: This is a personal summary and interpretation based on a YouTube video. It is not official material and not endorsed by the original creator. All rights remain with the respective creators.

This document summarizes the key takeaways from the video. I highly recommend watching the full video for visual context and coding demonstrations.

Before You Get Started

  • I summarize key points to help you learn and review quickly.
  • Simply click on Ask AI links to dive into any topic you want.

AI-Powered buttons

Teach Me: 5 Years Old | Beginner | Intermediate | Advanced | (reset auto redirect)

Learn Differently: Analogy | Storytelling | Cheatsheet | Mindmap | Flashcards | Practical Projects | Code Examples | Common Mistakes

Check Understanding: Generate Quiz | Interview Me | Refactor Challenge | Assessment Rubric | Next Steps

What is NestJS and Why Use It?

NestJS is a progressive Node.js framework that uses TypeScript by default and follows an opinionated, Angular-inspired architecture (modules, controllers, providers). It sits on top of Express (or Fastify) and brings structure, scalability, and built-in support for things like dependency injection, decorators, and modular design.

Key advantages over plain Express:

  • Opinionated → less “spaghetti code” in large apps
    Built-in TypeScript + decorators
    Clear separation of concerns (MVC-like)
    Easy to test and maintain
    Huge ecosystem and CLI

Ask AI: What is NestJS and its advantages

Prerequisites

You should already be comfortable with:

  • Node.js & Express basics
  • TypeScript (classes, interfaces, decorators)
  • Object-Oriented Programming (classes, inheritance, constructors)

If any of those feel shaky, pause and brush up first — the course moves fast.

Ask AI: NestJS prerequisites

Project Setup & Nest CLI

# Install CLI globally
npm i -g @nestjs/cli

# Create new project
nest new project-name
# Choose npm/yarn/pnpm → picks npm by default

The CLI generates a ready-to-run TypeScript project with a clean structure.

Run with hot-reload:

npm run start:dev

Ask AI: NestJS CLI setup

Core Concepts: Modules, Controllers, Providers

Everything revolves around three building blocks:

  • Module (@Module) → groups related code
  • Controller (@Controller) → handles routes & HTTP requests
  • Provider (@Injectable service) → business logic, injectable anywhere

Generate with CLI:

nest g module users
nest g controller users
nest g service users

The CLI automatically registers them in the module and imports the module into AppModule.

Ask AI: NestJS modules controllers providers

Controllers & Routing in Depth

@Controller('users')
export class UsersController {
  @Get()
  findAll() { ... }

  @Get(':id')
  findOne(@Param('id') id: string) { ... }

  @Post()
  create(@Body() createUserDto: any) { ... }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateUserDto: any) { ... }

  @Delete(':id')
  remove(@Param('id') id: string) { ... }
}

Important notes:

  • Route order matters — specific routes first, dynamic (:id) later
  • Use @Query(), @Param(), @Body() decorators to extract data
  • Nest returns proper status codes (201 for POST, etc.)

Ask AI: NestJS controller routing and decorators

Providers / Services & Dependency Injection

Services hold the actual logic and are injected into controllers:

@Injectable()
export class UsersService {
  private users = [/* mock data */];

  findAll(role?: 'INTERN' | 'ENGINEER' | 'ADMIN') { ... }
  findOne(id: number) { ... }
  create(user: CreateUserDto) { ... }
  update(id: number, updateUserDto: UpdateUserDto) { ... }
  remove(id: number) { ... }
}

Controller injection:

constructor(private readonly usersService: UsersService) {}

Nest creates a singleton instance by default → true DI benefits.

Ask AI: NestJS services and dependency injection

DTOs + ValidationPipe (Data Transfer Objects)

Never let raw request bodies hit your service. Use class-validator + class-transformer:

// create-employee.dto.ts
export class CreateEmployeeDto {
  @IsString()
  @IsNotEmpty()
  name: string;

  @IsEmail()
  email: string;

  @IsEnum(['INTERN', 'ENGINEER', 'ADMIN'])
  role: string;
}

Enable globally in main.ts:

app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }));

Now bad payloads automatically return 400 with clear messages.

Ask AI: NestJS DTOs and ValidationPipe

Prisma Integration (ORM) + Neon Database

Install:

npm i prisma @prisma/client
npm i -D prisma
npx prisma init

Set DATABASE_URL to a PostgreSQL connection string (Neon gives you one).

Define schema.prisma → Employee model → npx prisma generate

Create PrismaService that extends PrismaClient and implements OnModuleInit.

Use in EmployeeService:

this.prisma.employee.create({ data }) 
this.prisma.employee.findMany({ where: { role } })

Ask AI: NestJS with Prisma and Neon

Full CRUD Generation with Nest CLI + Prisma

nest g resource employees
# Choose REST API → TypeScript → include CRUD

The CLI creates module, controller, service, DTOs and wires everything. Then just replace service methods with Prisma calls → instant type-safe CRUD.

Ask AI: NestJS CLI resource generation with Prisma

Global Prefix, CORS, Rate Limiting, Logging & Exception Filters

// main.ts
app.setGlobalPrefix('api');
app.enableCors(); // or with config object

Rate limiting with @nestjs/throttler:

ThrottlerModule.forRoot({ ttl: 60000, limit:100 })
@Throttle({ default: { ttl: 1000, limit: 3 } })

Custom logger extending ConsoleLogger → writes to logs/my-log-file.txt (tab-delimited).

Global exception filter that catches everything, formats consistent JSON errors, logs with context, and handles Prisma validation errors specially (422).

Ask AI: NestJS global config CORS throttler logger exception filter


About the summarizer

I'm Ali Sol, a Backend Developer. Learn more: