NestJS and Building a CRUD REST API

Jul 18, 2024

Lecture on NestJS and Building a CRUD REST API

Introduction to NestJS

  • NestJS is a framework for building scalable Node.js web applications using TypeScript.
  • The lecture will cover building a CRUD REST API using NestJS.
  • Instructor: Vladimir, a full-stack software developer.
  • The course aims to build a production-like app, including authentication and relational databases using Prisma, and end-to-end tests.

Teaching Approach

  • Hands-on coding approach.
  • Code will be available in a GitHub repository.
  • Questions can be asked in the comment section or on the channel "Code with Vlad".
  • Basic understanding of JavaScript ES6 and TypeScript is required but explanations will be provided step-by-step.

Overview of NestJS

What is NestJS?

  • NestJS is a backend framework for Node.js that fully embraces TypeScript.
  • It solves architectural problems encountered with Express.js by providing a structured way to build applications.
  • Uses Express.js under the hood but adds significant abstractions.
  • Emphasizes modularity and dependency injection.
  • Often referred to as “Angular for the backend.”

Why Use NestJS?

  • Structure: Provides a well-defined structure out of the box.
  • Modularity: Encourages breaking down applications into modules.
  • TypeScript Support: Built with TypeScript.
  • Functionality: Integrates well with GraphQL, microservices, REST APIs, and has good documentation and security practices.
  • Popularity: Rapidly growing and highly favored by employers due to its structured approach.

Getting Started

Prerequisites

  • Node.js (version 16 or higher with long-term support).
  • NestJS CLI installed globally via npm install -g @nestjs/cli.
  • A code editor, preferably VS Code.

Creating a New Project

  • Use the command nest new nest-js-api-tutorial to create a new project.
  • Choose a package manager, e.g., Yarn.
  • Structure provided by the CLI includes folders for sources and tests, and configuration files.

NestJS Concepts

Modules

  • Core of the Application: Organize and structure an application by features or areas of functionality.
  • Main Module: app.module.ts is the root module.
  • Feature Modules: Create feature-specific modules like auth module, user module, bookmarks module, etc.

Creating Modules

  • Classes annotated with the @Module decorator.
  • Can import other modules, controllers, and providers.
  • Feature modules example: Auth module for authentication logic, User module for user-related logic, Bookmarks module, and a Database module.

Controllers and Services

  • Controllers: Handle incoming requests and return responses to the client.
  • Services (Providers): Execute business logic and handle data-related tasks.
  • Create controllers and services manually first to understand the structure before using CLI generators.

Dependency Injection and Decorators

Dependency Injection

  • Allows passing instances of classes and services as dependencies.
  • Example: Inject authService into the AuthController to handle authentication tasks.

Decorators in NestJS

  • Simplify the definition and management of metadata and routes.
  • Examples: @Post, @Get, @Body, @Param, @Controller, @Injectable.

Building the CRUD API

Authentication Service

  • Implement login and signup functionalities using JWT (JSON Web Tokens).
  • Hashing Passwords: Use argon2 for password hashing and comparison.
  • JWT: Sign tokens with secrets and provide access tokens for client authentication.

Controllers and Routes

  • Define routes for signup, login, and user-specific actions like fetching user info and updating user details.
  • Protect routes using guards and strategies.
  • Implement and use custom decorators for cleaner code.

Database Integration

Using Prisma ORM

  • Prisma: A modern ORM for Node.js and TypeScript used for database abstraction and type-safe data handling.
  • Setting Up Database: Configure a PostgreSQL database using Docker and Docker Compose.
  • Schema Definition: Define models in Prisma schema file and generate migrations.
  • Handling Models and Relationships: Define relationships and data models for users and bookmarks.

Applying Migrations and Seeding Data

  • Migrations: Use Prisma migrate commands to push schema changes to the database.
  • Seeding Data: Use custom scripts to seed initial development data.

Testing the Application

Types of Testing

  • Unit Testing: Testing individual functions or methods, often using mocks for dependencies.
  • Integration Testing: Testing multiple components together to ensure they work as expected.
  • End-to-End (E2E) Testing: Testing the full flow of the application to simulate user interactions.

Implementing Tests with Jest and Pactum

  • Setup Testing Environment: Configure Jest for end-to-end tests and resetting database state between test runs.
  • Running Tests: Use Pactum to define and execute API tests, ensuring the application behaves as expected.
  • Automating Tests: Setup scripts to automate running tests and managing test database.
  • Validating Tokens and Auth: Test JWT token generation and validation for secure routes.

Performance and Security

  • Optimize performance with clustering and proper resource management, potentially using PM2 for process management.
  • Secure the API by validating inputs, handling errors correctly, and ensuring sensitive data is protected.

Conclusion

  • The course demonstrated setting up a full-featured, secure, and scalable NestJS application.
  • Covered the entire development lifecycle from setup, coding, database integration, testing, and optimization for production.
  • Encourages exploration of advanced topics like further test automation and deploying NestJS applications.