🌱NestJS Foundations

Learn the fundamentals of NestJS, understand its core philosophy, and set up a rock-solid development environment.

πŸ“¦ Project Setup & CLI Magic

Welcome to NestJS Foundations! In this chapter, we'll dive into setting up your first NestJS project and mastering the CLI. You'll learn how to leverage the NestJS CLI to scaffold projects efficiently, understand the folder structure, and utilize TypeScript effectively.

πŸ’‘ Project Setup: Creating Your First NestJS App

Let's start by creating a new NestJS project using the CLI. This will give you a solid foundation to build upon.

$ npm install -g @nestjs/cli
$ nest new my-project

The CLI creates a well-structured project with all necessary files. The main components include:

  • AppModule - The root module of your application.
  • Main file - Where the application starts.
  • package.json - Dependencies and scripts configuration.

πŸ’‘ Understanding the Project Structure

The folder structure is designed to promote modularity and separation of concerns. Key directories include:

  • src/ - Source code directory.
  • src/app.module.ts - Root module configuration.
  • src/main.ts - Application entry point.

πŸ’‘ CLI Magic: Generating Modules, Controllers, and Services

NestJS CLI provides powerful commands to generate boilerplate code. Here are the essential commands:

  • $ nest generate module <name> - Generate a new module.
  • $ nest generate controller <name> - Generate a new controller.
  • $ nest generate service <name> - Generate a new service.
// Example: Generating a user module
$ nest generate module user

These commands create the necessary files and update your module structure, promoting efficient development.

πŸ’‘ Key Concepts to Remember

  • Always start with nest new projectName for a fresh project.
  • Use CLI commands to maintain consistency and best practices.
  • Understand the generated files and their purposes.

πŸ’‘ Environment Configuration

NestJS supports environment variables for different environments. Configure your settings using:

// Development
$ npm run start
// Production
$ npm run start:prod

Create .env and .env.example files for development and production configurations.

// .env
PORT=3000
DB_HOST=localhost
// .env.example
PORT=3000
DB_HOST=localhost

πŸ’‘ Best Practices for Project Setup

  • Organize modules by feature or domain.
  • Keep the root module clean and focused on core functionality.
  • Use environment variables to manage sensitive information.

🧠 Understanding the Architecture

Welcome to Understanding the Architecture in NestJS! This chapter will guide you through the core principles and components that make NestJS a powerful framework for building scalable applications. We'll explore how decorators, dependency injection, and modular architecture work together to create maintainable systems.

πŸ’‘ The Core Architecture

NestJS is built on the concept of modular architecture, inspired by Angular. It uses a combination of decorators and dependency injection to organize components into reusable modules. This approach allows you to create applications that are: scalable, maintainable, and testable.

  • Decorators: Transform classes and methods into NestJS components
  • Modules: Organize related components and dependencies
  • Services: Implement business logic with dependency injection
  • Controllers: Handle HTTP requests and responses

πŸ’‘ Key Concepts in NestJS Architecture

  • Decorators define the role of a class or method (e.g., @Controller, @Service)
  • Modules bundle related components and configure dependencies
  • Dependency Injection automatically provides required services to components
  • Metadata enables runtime reflection for decorator configurations

βœ… Exploring Modules in NestJS

Modules are the building blocks of a NestJS application. They allow you to organize your code into logical units and control their dependencies. A typical module structure includes:

  • Imports: Other modules needed by this module
  • Controllers: HTTP endpoints exposed by the module
  • Services: Business logic components used within the module
  • Exports: Components made available to other modules
// Example module
declare module 'PostsModule' {
  exports = {
    controller: PostsController,
    service: PostsService
  };
}

// Module configuration
@Module({
  imports: [TypeOrmModule.forFeature([Post])],
  controllers: [PostsController],
  providers: [PostsService]
})
export class PostsModule {}

πŸ’‘ Understanding Services and Controllers

In NestJS, the service layer contains your business logic, while the controller handles incoming HTTP requests. Services are injected into controllers via dependency injection, allowing for loose coupling and easier testing.

// Service implementation
@Injectable()
export class PostsService {
  constructor(
    @InjectRepository(Post)
    private postRepository: Repository<Post>
  ) {}

  async findAll(): Promise<Post[]> {
    return this.postRepository.find();
  }
}

// Controller implementation
@Controller('posts')
export class PostsController {
  constructor(private postsService: PostsService) {}

  @Get()
  async getAllPosts(): Promise<Post[]> {
    return this.postsService.findAll();
  }
}

βœ… Dependency Injection in NestJS

NestJS uses a powerful dependency injection system that allows you to:

  • Declare dependencies in your service constructors
  • Use decorators like @Inject() and @Injectable()
  • Provide custom providers for configuration values
  • Access databases and external services through injected repositories

❌ Common Pitfalls to Avoid

  • Don't place business logic directly in controllers
  • Avoid mixing service and controller responsibilities
  • Don't use global modules unnecessarily
  • Never inject raw HttpServer instances into services

πŸ’‘ Real-World Application: Blogging System

Let's consider a modular blogging system built with NestJS. This application would typically include:

  • User Module: Handles authentication and user profiles
  • Post Module: Manages blog posts, comments, and likes
  • Category Module: Organizes posts into different categories
  • Admin Module: Provides backend tools for content management

πŸ’‘ Conclusion

Understanding the architecture of NestJS is crucial for building robust applications. By leveraging decorators, dependency injection, and modular design, you can create systems that are easy to maintain and scale. Keep these principles in mind as you progress through this course!

Quiz

Question 1 of 10

Which command is used to create a new NestJS project?

  • nest new
  • nest create
  • npm init
  • node create