Nest js
The article is Written by Md Tareq Shah Alam.
Feel free to share..
Nest js is a progressive node framework. It doesn't give you a lot of structure. This is efficient when you have already a lot of sturcture in the backend.
The syntax or the structure is very similar to Angular. To install nest, you will be needed node js into your system at first as it is a node framework. The installation process is here....
In the structure of the nest project, you will see that it uses typescript in the source folder.
To see the structure, first follow the documentation from the given link, install nest into your system. Now, you have nest and the project into your system.
img: Nest structure |
In the src foleder you will get the ts files where you will do your project.
You should install controller into your project by this command:
$ nest g controller items
Then you will get this folder:
img: Controllers |
To run the server, you can use - $ npm start. If you will use this command, then you have to stop the server and restart it all the time when you will make change into your project.
But it is obvious that you will change the code consistantly for that reason you will be needed something like nodemon, what you have used into express js. The command should be: $ npm run start:dev
If you want to see the requests from the path, you can use post man.
From controller.ts, you will be able to see the path controller:
This is a basic NestJS controller file (cats.controller.ts). Let's break it down:
- import { Controller, Get, Post, Body } from '@nestjs/common';: Import necessary decorators from the @nestjs/common package to define the controller and its methods.
- import { CreateCatDto } from './create-cat.dto';: Import the DTO (Data Transfer Object) used for creating a cat. This DTO should define the structure of data expected when creating a cat.
- import { CatsService } from './cats.service';: Import the service responsible for handling business logic related to cats.
- import { Cat } from './interfaces/cat.interface';: Import the interface defining the structure of a cat object.
- @Controller('cats'): Decorate the class with @Controller to define the base route for the controller's endpoints.
- export class CatsController { ... }: Define the CatsController class.
- constructor(private readonly catsService: CatsService) {}: Inject the CatsService into the controller using dependency injection.
- @Post(): Decorate the create method with @Post() to define a POST endpoint at the base route (/cats). This method will handle creating a new cat.
- async create(@Body() createCatDto: CreateCatDto) { ... }: Define the create method, which takes the data from the request body (createCatDto) and passes it to the catsService for creation.
- @Get(): Decorate the findAll method with @Get() to define a GET endpoint at the base route (/cats). This method will handle fetching all cats.
- async findAll(): Promise<Cat[]> { ... }: Define the findAll method, which returns a Promise of an array of Cat objects fetched from the catsService.
- This controller follows the basic structure of a NestJS controller, where HTTP methods are defined as controller methods and are responsible for handling requests and delegating business logic to the corresponding service.
Request Objects
To request objects using a controller in NestJS, you typically define route parameters or query parameters in your controller methods. These parameters allow you to retrieve data from the client's request and use it within your controller methods. Here's how you can request objects using a controller in NestJS:
1. Route Parameters: Route parameters are part of the URL path and are used to identify a specific resource. You can define route parameters in your controller method signature by adding parameters enclosed in curly braces {} in your route path.
In this example, the :id route parameter is defined in the route path. The @Param('id') decorator is used to extract the value of the id parameter from the request URL and pass it to the findOne method of the catsService.
2. Query Parameters: Query parameters are part of the URL query string and are used to provide additional information to the server. You can define query parameters in your controller method signature by adding parameters decorated with @Query().
In this example, the @Query() decorator is used to extract all query parameters from the request URL and pass them as an object to the findAll method of the catsService.
By using route parameters and query parameters in your controller methods, you can request objects from the client's requests and use them within your NestJS application.
Hardcoded Data
Hardcoded data refers to data that is directly written into the source code of a program rather than being dynamically generated or retrieved from an external source at runtime. In the context of a NestJS controller, hardcoded data can be used to provide sample or default data for testing purposes, prototyping, or when external data sources are not available or unnecessary.
Here's an example of how hardcoded data can be used in a NestJS controller:
In this example:
The CatsController class defines a private array cats containing hardcoded data representing cat objects.
The findAll method is decorated with @Get() to define a GET endpoint at the /cats route.
When the /cats endpoint is accessed, the findAll method returns the cats array, providing hardcoded data as the response.
Hardcoded data can be useful during development and testing phases, allowing developers to quickly prototype functionality without relying on external data sources. However, it's important to replace hardcoded data with dynamic or external data sources in production code to ensure flexibility, scalability, and maintainability of the application.
Find all and Find one
In a NestJS controller, the findAll and findOne methods are commonly used to retrieve data from a service and return it as a response to client requests. Let's describe each method:
findAll Method:
Description: The findAll method is a controller method decorated with @Get() to define a GET endpoint at the /cats route.
Purpose: It retrieves all cats from the catsService and returns them as a response.
Usage: When a GET request is made to /cats, this method is invoked. It calls the findAll method of the catsService to fetch all cats from a data source (e.g., database) and returns them to the client.
findOne Method:
Description: The findOne method is a controller method decorated with @Get(':id') to define a GET endpoint at the /cats/:id route. It uses a route parameter :id to identify the specific cat to retrieve.
Purpose: It retrieves a single cat based on the provided ID from the catsService and returns it as a response.
Usage: When a GET request is made to /cats/:id (e.g., /cats/123), this method is invoked with the ID parameter extracted from the request URL. It calls the findOne method of the catsService with the provided ID to fetch the corresponding cat from a data source and returns it to the client.
In summary, findAll retrieves all cats, while findOne retrieves a single cat by ID. These methods facilitate data retrieval and help build RESTful APIs in NestJS applications.
MongoDB
MongoDB is a popular open-source, NoSQL database management system (DBMS) known for its flexibility, scalability, and performance.
NoSQL, which stands for "Not Only SQL," is a term used to describe a broad category of database management systems (DBMS) that diverge from the traditional relational database management systems (RDBMS) model. NoSQL databases are designed to handle large volumes of unstructured, semi-structured, or structured data and offer flexible schemas, horizontal scalability, and high availability. Here are some key characteristics of NoSQL databases.
To config mongodb to your nest project, you should install mongoose to your npm at first. The command is: $ npm install --save mongoose
[ In the app.module.ts, you should set this db configuration for nest js db config. The configuration document is here. Just copy and paste it into the file. ]
The connect config code from MongoDB, you can either copy from mongodb server and paste it into the default app.module.ts file or you can create another folder and create a ts file and paste it into that which should be more efficient.
You can learn MongoDB from here... I also learned from here.
Thats all about beginning concept about nest js. Thank you. Assalamu Alaikum...
Comments
Post a Comment