用 Nest.js 開發 API 吧 (二) - 專案架構


Posted by AlanSyue on 2020-11-22

上一篇說明了我為什麼選用 Nest.js 開發,之後安裝並啟動了專案。今天要來分享 Nest.js 的專案架構。

Nest.js 的基本架構主要分為:

  1. Main
  2. Module
  3. Controller
  4. Service

Main

可以從 src/main.ts 檔案來看,執行 yarn start:dev 後的進入點。

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

從程式碼可以看出來 main.ts 會決定要使用哪個 module 以及 port,預設是使用 AppModule 以及 3000 port

Module

上一篇有提到 Nest.js 有許多借鑒 Angular 的風格,其中 Module 就類似於 Angular 的 NgModule,讓我們把類型或功能相似的程式封裝成一個一個不同的模組。如果到 app.module.ts 檔案可以看到檔案分成三個部分:

1. import

the list of imported modules that export the providers which are required in this module

import 主要是可以掛載並導入到 providers 所需要的 modules

2. controller

the set of controllers defined in this module which have to be instantiated

此 module 需要呼叫的 Controller

3. providers

the providers that will be instantiated by the Nest injector and that may be shared at least across this module

此 module 需要被呼叫並注入依賴的服務,這些服務可以在此 module 被共用

Controller

控制器,從 Module 被呼叫,並擁有基本路由設定,主要負責接收 client 端的 requests 以及 response。

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}

app.controller.ts 程式碼可以看到:

  1. 透過 @Controller 可以定義此檔案為 Controller
  2. @Get() 可以決定請求方式為 get,route 為 http://localhost:3000/,舉例若 @Post('users'),請求方式便為 Post,route 為 http://localhost:3000/users

Service

service 主要處理商業邏輯的操作,透過注入依賴的方式讓 Controller 和其他 Service 可以使用。

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }
}

app.service.ts 的程式碼可以看到 @Injectable() 定義此類別為 service,並定義 getHello() 這個 method,會回傳 Hello World 這個 string。

我們可以看剛剛 app.controller.ts 這個控制器有呼叫 app.service.tsgetHello() method。

return this.appService.getHello();

所以如果 request http://localhost:3000/ 就會接收到 Hello World 這個字串 (可以參考上一篇啟動畫面的結果)

小結

今天介紹了 Nest.js 的基本架構

  1. Main
  2. Module
  3. Controller
  4. Service

如果文章有任何錯誤或建議,歡迎告知!

NEXT:用 Nest.js 開發 API 吧 (三) - Controller


#nest.js #node.js #module #controller #service #structure







Related Posts

GDB Cheatsheet

GDB Cheatsheet

React 入門 5 - State Lifting

React 入門 5 - State Lifting

Python Table Manners - 測試 (二)

Python Table Manners - 測試 (二)


Comments