Nest.js is a powerful and flexible framework for building scalable and maintainable server-side applications using JavaScript or TypeScript. It leverages the capabilities of the popular Node.js platform and combines it with the robustness of best-practices inspired by Angular.
In this blog post, we will be exploring the basics of Nest.js, setting up a new project, understanding its core concepts, and creating a simple RESTful API.
Here are a few reasons why Nest.js stands out among other server-side frameworks:
With these benefits in mind, let's dive into setting up a new Nest.js project.
To get started with Nest.js, you need to have Node.js installed on your machine. If you don't have Node.js installed, you can download it from the official website.
Once you have Node.js installed, you can create a new Nest.js project by following these steps:
The Nest CLI is a command-line tool that helps you create, manage, and build your Nest.js projects. To install the Nest CLI, open a terminal and run the following command:
npm install -g @nestjs/cli
This command installs the Nest CLI globally on your machine, making it available for use in any directory.
After installing the Nest CLI, you can create a new Nest.js project by running the following command:
nest new my-nest-project
Replace my-nest-project
with the desired name for your project. The Nest CLI will prompt you to choose a package manager (npm or yarn) and then create the necessary files and folders for your project.
Once the project is created, navigate to the project directory by running:
cd my-nest-project
To start your Nest.js application, run the following command inside the project directory:
npm run start
This command starts your application in development mode, which means that it will automatically reload when you make changes to your code. You should see the following output:
[Nest] 12345 - 12/34/56 Starting compilation...
[Nest] 12345 - 12/34/56 Compilation complete. Starting Nest application...
[Nest] 12345 - 12/34/56 Nest application successfully started
By default, your Nest.js application will be running on http://localhost:3000. You can test your application by visiting this URL in your browser or using a tool like Postman to make HTTP requests.
Now that you have a Nest.js project set up, let's take a look at some of the core concepts that you'll be working with when building your application.
In Nest.js, a module is a class decorated with the @Module()
decorator. Modules are used to organize your application into smaller, reusable pieces. A module can import other modules, declare components, and provide them to other modules.
Here's an example of a simple module:
import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';
@Module({
imports: [],
controllers: [CatsController],
providers: [CatsService],
})
export class CatsModule {}
In this example, the CatsModule
imports the CatsController
and CatsService
components and provides them to other modules that might need them.
A controller is a class decorated with the @Controller()
decorator. Controllers are responsible for handling incoming HTTP requests and returning responses. They define routes and their associated request handling logic.
Here's an example of a simple controller:
import { Controller, Get } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
}
In this example, the CatsController
defines a single route, /cats
, which responds to HTTP GET requests with the text "This action returns all cats".
A provider is a class or a factory function that can be used to create and manage dependencies in your application. Providers are decorated with the @Injectable()
decorator and can be injected into other components using Nest.js's Dependency Injection system.
Here's an example of a simple provider:
import { Injectable } from '@nestjs/common';
@Injectable()
export class CatsService {
private readonly cats: string[] = [];
create(cat: string) {
this.cats.push(cat);
}
findAll(): string[] {
return this.cats;
}
}
In this example, the CatsService
is a provider that manages a list of cats. It provides methods for adding new cats and retrieving all cats.
To demonstrate how to use these core concepts, let's create a simple RESTful API for managing cats. We'll start by updating our CatsService
to work with a Cat
interface:
import { Injectable } from '@nestjs/common';
import { Cat } from './interfaces/cat.interface';
@Injectable()
export class CatsService {
private readonly cats: Cat[] = [];
create(cat: Cat) {
this.cats.push(cat);
}
findAll(): Cat[] {
return this.cats;
}
}
Next, we'll create a new file called cat.interface.ts
in the src/cats/interfaces
folder and define the Cat
interface:
export interface Cat {
id: number;
name: string;
age: number;
breed: string;
}
Now, let's update our CatsController
to use the CatsService
for handling requests:
import { Controller, Get, Post, Body } from '@nestjs/common';
import { CatsService } from './cats.service';
import { Cat } from './interfaces/cat.interface';
@Controller('cats')
export class CatsController {
constructor(private readonly catsService: CatsService) {}
@Post()
create(@Body() cat: Cat): void {
this.catsService.create(cat);
}
@Get()
findAll(): Cat[] {
return this.catsService.findAll();
}
}
In this updated version of the CatsController
, we've added a new route for creating cats using HTTP POST requests. We've also updated the findAll()
method to return an array of Cat
objects instead of a string.
With these changes, our simple RESTful API is complete. You can test the API using a tool like Postman or by creating a simple front-end application that consumes the API.
In this blog post, we've covered the basics of Nest.js, including setting up a new project, understanding its core concepts, and creating a simple RESTful API. Nest.js is a powerful and flexible framework that can help you build scalable and maintainable server-side applications using JavaScript or TypeScript.
To learn more about Nest.js and its features, you can check out the following resources:
Happy coding!