Skip to main content

NestJS is a progressive Node.js framework

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

Popular posts from this blog

What is Branching in python and how to use with examples

  In Python,   branching   refers to the ability to control the flow of your program based on certain conditions.   This allows your code to make decisions and execute different blocks of code depending on the outcome of those conditions. There are three main types of branching statements in Python: 1.  if  statement: The  if  statement allows you to execute a block of code only if a certain condition is True. The basic syntax is: Python if condition: # code to execute if condition is True Here's an example: Python age = 25 if age >= 18 : print( "You are an adult." ) else : print( "You are not an adult." ) 2.  if...elif...else  statement: This allows you to check multiple conditions and execute different code blocks for each condition. The  elif  branches are checked sequentially until one of them is True. If none are True, the  else  block is executed (optional). Python score = ...

What is the difference between Eclipse IDE for Java EE developers and Eclipse IDE for Java?

The main difference between Eclipse IDE for Java EE Developers and Eclipse IDE for Java lies in their focus and pre-installed functionalities: Eclipse IDE for Java: Focus:  General Java development, including Swing applications, console applications, and core Java libraries. Features:  Includes plugins for Java development such as syntax highlighting, code completion, debugging tools,and refactoring capabilities. Lacks:  Plugins specifically for web development, database integration, and enterprise-level functionalities. Eclipse IDE for Java EE Developers: Focus:  Development of Java Enterprise Edition (Java EE) applications, web applications, and enterprise-grade software. Features:  Comes pre-installed with plugins for JSP, Servlet development, JPA and Data Tools, JSF, Maven and Gradle build tools, Git version control, and more. Includes:  Tools for debugging, web services,...

Is JavaFX worth to learn in 2024? What are the advantages and disadvantages?

  Whether JavaFX is worth learning in 2024 depends on your specific goals and interests.   Here's a breakdown of its advantages and disadvantages to help you decide: Advantages: Platform-independent:  JavaFX applications can run on Windows, macOS, Linux, and some mobile platforms.This cross-platform compatibility can be valuable if you want to target a wider audience. Modern UI framework:  JavaFX offers a rich set of UI components and features for building modern and visually appealing applications. It includes animation, effects, transitions, and support for touch gestures. Integration with Java:  JavaFX integrates seamlessly with the Java ecosystem, allowing you to leverage existing Java libraries and tools. This can be helpful if you're already familiar with Java development. Large community:  JavaFX has a large and active community of developers, providing resources, tutorials, and support. Dis...