Getting to know NestJS
Let’s first look at the official website’s introduction to NestJS .
Nest (NestJS) is a development framework for building efficient, scalable Node.js server-side applications. It leverages the progressive enhancement capabilities of JavaScript, uses and fully supports TypeScript (still allowing developers to develop in pure JavaScript), and combines OOP (Object Oriented Programming), FP (Functional Programming) and FRP (Functional Reactive Programming) .
Under the hood, Nest is built on powerful HTTP server frameworks such as Express (default), and can also be configured to use Fastify !
Nest raises a level of abstraction above these common Node.js frameworks (Express/Fastify), but still exposes the API of the underlying framework directly to developers. This frees developers to use the myriad of third-party modules available for the underlying platform.
From this text, the following points can be learned:
- NestJS is a server-side application development framework based on Node.js
- Fully supports TypeScript , and can also be developed using pure JS
- Supports multiple programming paradigms such as OOP and FR
- The bottom layer handles HTTP requests, or use Express (default) , or switch to Fastify
- There are countless third-party modules available
Let's get started with the development of NestJS applications.
quick initialization
Nestjs officially provides a useful scaffolding tool that can be used to quickly create, develop and build a Nestjs application.
First install the scaffolding tool globally:
npm install -g @nestjs/cli
View the scaffolding version number:
nest -v
9.1.8
Create the project using the command provided by scaffolding new
:
nest new hello-nest
The command line will prompt you to choose a package management tool you want. This article uses Pnpm:
The scaffolding tool creates a lot of files, and then installs dependencies:
Wait a minute, here's what the project looks like after project initialization is complete:
According to the prompt, enter the project directory and execute the startup command to run a Nestjs application:
$ cd hello-nest
$ pnpm run start
In the command line window, there are some printed information, we can simply look at it.
> hello-nest@0.0.1 start D:\2023code\hello-nest
这一行是项目的名字以及版本号,和项目所在路径
> nest start
这一行是启动项目的命令
下面是应用运行的日志信息
[Nest] 42416 - 2023/01/14 14:32:29 LOG [NestFactory] Starting Nest application...
NestFactory(Nest 工厂类)日志,启动了 Nest 应用
[Nest] 42416 - 2023/01/14 14:32:29 LOG [InstanceLoader] AppModule dependencies initialized +24ms
InstanceLoader(实例加载器类) 日志,App 模块的依赖完成初始化
[Nest] 42416 - 2023/01/14 14:32:29 LOG [RoutesResolver] AppController {
/}: +5ms
RoutesResolver(路由解析器类) 日志,App 控制器建立了 ‘/’ 这个路由
[Nest] 42416 - 2023/01/14 14:32:29 LOG [RouterExplorer] Mapped {
/, GET} route +2ms
RouterExplorer(路由管理器类) 日志,完成了 'GET /' 路由的映射
[Nest] 42416 - 2023/01/14 14:32:29 LOG [NestApplication] Nest application successfully started +1ms
NestApplication(Nest 应用程序类) 日志,Nest 应用成功启动
So now, the browser can access /
this route.
Hello, world
The default port of the Nest application is 3000, open the browser, visit localhost:3000
, you can see the following interface:
Next, let's look at the source code and see how NestJS responds Hello, World
to the browser.
Analyze Hello, World
Below is the directory structure of the Nest project we just created.
Let's focus on the directory first src
, there are five files under it .ts
, namely:
-
app.controller.spec.ts: unit test file for the App Controller
-
app.controller.ts: Controller for the App module
-
app.module.ts: App module, which is also the root module of the Nest application
-
app.service.ts: The service layer code of the App module
-
main.ts: Nest application entry file, used to create a Nest application instance and start the application
From main.ts it looks like
Open src/main.ts
, this is the entry file of the Nest application. The code is simple:
import {
NestFactory } from '@nestjs/core';
import {
AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
This file encapsulates a bootstrap
function for creating Nest applications. Internally call the create method of the NestFactory factory class, pass in the AppModule, and create an application instance. Finally, the application calls the listen method to monitor port 3000 to complete the start of the web service.
If you have written Vue, you can main.js
make an analogy between this file and the entry file of the Vue project. NestFactory.create
Like createApp
methods, AppModule
modules are like App.vue
root components. If you use Express or Koa, listen
not to mention the method, it can be compared to the component's mount mount
method, which is the last step in creating an application.
app.module.ts
The Nest application is based on the module Module. Modules have two core members, controllers and providers . Modules can be understood as components in the front-end Vue project . main.ts
Export an AppModule class, which is the root module of the Nest application, just like the root component in the Vue application.
import {
Module } from '@nestjs/common';
import {
AppController } from './app.controller';
import {
AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {
}
In this file, the controller AppController and the service AppService of the App module are imported , and then @Module
the AppModule class is declared as a module through a decorator (similar to annotations in Java) .
The decorator @Module
receives several properties, controllers
and providers
. The former receives the controller, and the latter receives the provider. There are many providers in Nest, and the AppService in the code is a kind of provider. Through the decorator and these two attributes, a module can organize controllers and services together .
app.controller.ts
This is the controller layer code of the App module, which is used to receive user requests, call the service layer for processing, and then return the results to the client.
import {
Controller, Get } from '@nestjs/common';
import {
AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {
}
@Get()
getHello(): string {
return this.appService.getHello();
}
}
It first imports the two decorators provided by the Nestjs core package, and then imports the service class of the App module. Declare the class as a controller via @Controller
the decorator . AppController
The construction method of the class in the code is a shorthand mode. Its function is to mount the instance of the AppService service class to the instance of the controller , and it is also a private member. It is expressed in pseudocode:
class AppController {
constructor() {
this.appService = new AppService()
}
}
But in fact, the AppService service class is not instantiated here, but is managed by the dependency injection container as a dependency.
So it can be called directly in the member method of the class this.appService
.
Then @Get
the decorator is used to declare getHello
the method, indicating that this method is used to process HHTP
the GET
request. @Controller
Both and @Get
can receive parameters of string type to splice routes, such as @Controller('news')
and @Get('list')
, the spliced route is /news/list
. The decorators in the example code all omit parameters, which default to an empty string, and the corresponding route is the root route /
. Just like in Express:
app.get('/', getHello)
app.get('/news/list', getNewsList)
getHello
The method internally calls getHello
the method of the App service layer, so it's time to look at app.service.ts
it next.
app.service.ts
This is the service layer file of AppModule, and it is also where the business is actually handled.
import {
Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
This file imports a @Injectable
decorator that declares the AppService type as a "provider". There are many kinds of providers in Nest, "service" here is one of the most commonly used providers. This involves the concept of dependency injection. The role of the provider in dependency injection is the class that can be injected into the container.
This code can be simply understood that after using this decorator, the instance of the AppService class can be used directly in the controller without manual import and instantiation .
AppService
The class has a getHello
method that returns Hello, World!
a string, and that's the one we see in the browser. The string it returns is handed over to the App controller, and the controller returns it to the browser. So far, a complete process has been completed.
Summarize
This article introduces the use of @nest/cli scaffolding to quickly create and start a Nest application, then analyzes the "Hello, World" sample code, and briefly introduces some TypeSscript syntax, such as decorators, and some Nest concepts. I believe that after seeing this, everyone basically understands the process that the Nest app has gone through after receiving the user request and completed the response.
See you in the next article.