Sling Academy
Home/Node.js/Mastering NestJS CLI: A Practical Guide

Mastering NestJS CLI: A Practical Guide

Last updated: December 31, 2023

Introduction

Embark on a journey to master the NestJS CLI, an indispensable toolset that streamlines the development process of building efficient, reliable, and scalable server-side applications.

Getting Started with NestJS CLI

First things first, ensure you have Node.js installed. Then, install the NestJS CLI globally using npm:

npm install -g @nestjs/cli

Creating a new NestJS project is as simple as running:

nest new project-name

Generating NestJS Elements

The CLI allows you to generate various elements of your application such as controllers, providers, modules, and more:

1. Controllers route the incoming requests to the appropriate services. Generate one with:

nest g controller cats

2. Providers/Services are classes annotated with @Injectable(), which you can have injected into controllers or other services. Create a service by:

nest g service cats

3. Modules are classes annotated with @Module(), serving as a collective of controllers and services that can be organized in a feature-centric way. Generate a module easily:

nest g module cats

Building Blocks with Dependency Injection

To create connected and scalable applications, understanding the dependency injection system in NestJS is crucial. We define a Cats service:

import { Injectable } from '@nestjs/common';

@Injectable()
export class CatsService {
    findAll(): string[] {
        return ['Whiskers', 'Tom', 'Garfield'];
    }
}

We can inject this service into our Cats controller like so:

import { Controller, Get } from '@nestjs/common';
import { CatsService } from './cats.service';

@Controller('cats')
export class CatsController {
    constructor(private catsService: CatsService) {}

    @Get()
    findAll(): string[] {
        return this.catsService.findAll();
    }
}

Working with Configuration

Managing application configuration is easy with the NestJS ConfigModule, which allows for environment-based configurations:

import { ConfigModule } from '@nestjs/config';

@Module({
    imports: [ConfigModule.forRoot()],
})
export class AppModule {}

Access configuration variables using ConfigService:

import { ConfigService } from '@nestjs/config';

@Injectable()
export class CatsService {
    constructor(private configService: ConfigService) {}

    getDatabaseConnection(): any {
        const host = this.configService.get('DATABASE_HOST');
        // Connect to the database with the obtained 'host'
    }
}

Testing Your Application

NestJS CLI simplifies running unit tests. It’s configured to work with jest out-of-the-box:

npm run test

For end-to-end testing, execute:

npm run test:e2e

The NestJS CLI also supports interactive prompts, schematics and monorepo management. To explore the full potential of NestJS CLI, delve into the documentation.

Conclusion

Mastering the NestJS CLI transforms the app development process, offering a powerful suite of tools tailored for the modern developer. Its emphasis on ease of use and modularity results in clean, maintainable, and scalable code.

Next Article: How to Use Passport.js in NestJS

Previous Article: NestJS: Connecting to Different Databases Based on Routes

Series: Nest.js Tutorials: From Basics to Advanced

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates