NestJS is a progressive Node.js framework for building efficient, scalable, and reliable server-side applications. It uses TypeScript, a superset of JavaScript that adds static types and other features, and combines elements of object-oriented, functional, and reactive programming paradigms. NestJS is inspired by Angular, a popular framework for front-end development, and uses a similar modular architecture and dependency injection system. NestJS also supports Express and Fastify, two popular Node.js web frameworks, as well as TypeORM, an ORM that works with various databases.
To get started with NestJS, you need to install Node.js and the Nest CLI, a command-line tool that helps you create and manage NestJS projects. You can install Node.js from its official website, and the Nest CLI using npm, the Node.js package manager. To install the Nest CLI globally, run the following command in your terminal:
`$ npm i -g @nestjs/cli`
Once you have the Nest CLI installed, you can create a new NestJS project by running:
`$ nest new project-name`
This will create a new folder with the project name, and generate the initial files and dependencies for a NestJS application. You can then navigate to the project folder and start the development server by running:
`$ cd project-name`
`$ npm run start`
You can open your browser and go to http://localhost:3000/ to see the default response from the NestJS application.
To create a REST API with NestJS, you need to use controllers, providers, and modules, which are the main building blocks of a NestJS application. Controllers are responsible for handling incoming requests and returning responses to the client. Providers are plain JavaScript classes that can provide various functionalities, such as database access, validation, logging, etc. Modules are files that group together related controllers, providers, and other components, and provide a clear boundary of responsibility and encapsulation.
To create a controller, you can use the Nest CLI's generate command, which can also create other types of components, such as providers, modules, guards, etc. For example, to create a controller for books, you can run:
`$ nest generate controller books`
This will create a new file called books.controller.ts in the src folder, and register it in the app.module.ts file, which is the root module of the application. You can then use decorators, such as @Controller, @Get, @Post, @Put, @Delete, etc., to define the routes and methods for the controller. For example, to create a GET route for fetching all books, you can write:
```ts
import { Controller, Get } from '@nestjs/common';
@Controller('books')
export class BooksController {
@Get()
findAll() {
// return all books
}
}
```
To create a provider, you can also use the Nest CLI's generate command, and specify the type as service. For example, to create a service for books, you can run:
`$ nest generate service books`
This will create a new file called books.service.ts in the src folder, and register it in the app.module.ts file. You can then use the @Injectable decorator to mark the class as a provider that can be injected into other components, such as controllers. For example, to create a service that can fetch books from a database, you can write:
```ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class BooksService {
async findAll() {
// return books from database
}
}
```
To inject the service into the controller, you can use the constructor and specify the service as a parameter. For example, to inject the BooksService into the BooksController, you can write:
```ts
import { Controller, Get } from '@nestjs/common';
import { BooksService } from './books.service';
@Controller('books')
export class BooksController {
constructor(private booksService: BooksService) {}
@Get()
async findAll() {
return this.booksService.findAll();
}
}
```
To create a module, you can also use the Nest CLI's generate command, and specify the type as module. For example, to create a module for books, you can run:
`$ nest generate module books`
This will create a new file called books.module.ts in the src folder, and register it in the app.module.ts file. You can then use the @Module decorator to define the metadata for the module, such as the controllers, providers, and other modules that it imports or exports. For example, to create a module that groups together the BooksController and BooksService, you can write:
```ts
import { Module } from '@nestjs/common';
import { BooksController } from './books.controller';
import { BooksService } from './books.service';
@Module({
controllers: [BooksController],
providers: [BooksService],
})
export class BooksModule {}
```
To document your REST API with Swagger, you need to install and configure the @nestjs/swagger package, which integrates Swagger UI, a tool that automatically generates and displays API documentation based on your code. You can install the package using npm:
`$ npm install --save @nestjs/swagger swagger-ui-express`
You can then import the SwaggerModule and the DocumentBuilder classes in the main.ts file, which is the entry point of the application, and use them to create and serve a Swagger document. For example, to create a Swagger document with some basic information, such as the title, description, and version of the API, you can write:
```ts
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('Books API')
.setDescription('A simple REST API for books')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
await app.listen(3000);
}
bootstrap();
```
The last line of code, SwaggerModule.setup, will mount the Swagger UI on the /api path. You can open your browser and go to http://localhost:3000/api to see the Swagger UI for your API.
To add more details to your Swagger document, such as the parameters, responses, and models for your API endpoints, you can use decorators from the @nestjs/swagger package, such as @ApiParam, @ApiResponse, @ApiProperty, etc. For example, to add a parameter and a response for the GET route for fetching a single book by id, you can write:
```ts
import { Controller, Get, Param } from '@nestjs/common';
import { ApiParam, ApiResponse } from '@nestjs/swagger';
@Controller('books')
export class BooksController {
@Get(':id')
@ApiParam({ name: 'id', type: String })
@ApiResponse({ status: 200, description: 'The book with the matching id' })
findOne(@Param('id') id: string) {
// return the book with the given id
}
}
```
To learn more about NestJS, you can check out the [official documentation](^2^), the [NestJS Fundamentals Course](^4^), or the [Getting Started with NestJS tutorial](^3^). You can also find more resources and examples on the [NestJS website](^1^). I hope this helps you understand the basics of NestJS and how to create a REST API with it. 😊
Source: Conversation with Bing, 28/1/2024
(1) Documentation | NestJS - A progressive Node.js framework. https://docs.nestjs.com/.
(2) NestJS Fundamentals Course | NestJS. https://learn.nestjs.com/p/fundamentals.
(3) Getting Started with NestJS | DigitalOcean. https://www.digitalocean.com/community/tutorials/getting-started-with-nestjs.
(4) Nest.js Tutorial: Build your First REST API CRUD App with .... https://www.techiediaries.com/nestjs-tutorial-rest-api-crud/.
(5) undefined. https://github.com/nestjs/typescript-starter.git.
(6) github.com. https://github.com/thoraf20/nest-crud/tree/feef72aa0b2bbe0e713207ada78e635970b35560/src%2Fbooks%2Fbooks.module.ts.
(7) github.com. https://github.com/lamhq/snippets/tree/988dd23b7177d69596ec3a227dbb43514d170e77/nestjs%2Fswagger.md.
(8) github.com. https://github.com/fernandezllambi/trainer/tree/01d297ac56c7403b7a8215fd62cbc792f03a9b46/api%2Fsrc%2Fmain.ts.
(9) github.com. https://github.com/Tech-Couple/my-books-srv/tree/092aa294721d66849f57472d39b67fc03bd77580/src%2Fmain.ts.
(10) github.com. https://github.com/notiz-dev/notiz/tree/15fe7027a73541fcdb46ee36577dd5a87de636d1/content%2Fblog%2Fopenapi-in-nestjs.md.
Comments
Post a Comment