Controller負責處理Request及產生Response,資料庫存取或是商業邏輯(business logic)通常寫在Service class裡
商業邏輯以最簡單hello world為例
export class AppService {
sayHello(): string {
return 'Hello World! in App Service';
}
}
在app.controller.ts裡
...
import { AppService } from './app.service';
@Controller()
export class AppController {
// 宣告變數,型別為AppService
appService: AppService;
// 建立AppController實例時,一併建立AppService實例
constructor(){
this.appService = new AppService();
}
@Get()
sayHello(){
// 呼叫AppService的sayHello方法,回傳client
return this.appService.sayHello();
}
...
}
Postman結果
nest.js提供Dependency Injection(DI, 相依注入),可以不用每次要用AppService的時候都要new,讓nest.js DI機制幫我們處理相依class
nest.js的DI幾乎是從Angular整套借來用。
在app.module.ts中providers註冊AppService
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
到app.controller.ts,把要注入的AppService當作contructor參數
@Controller()
export class AppController {
appService: AppService;
// 將要注入的AppService當作constructor傳入參數
constructor(_appService: AppService){
// 把注入的AppService指定給controller變數
this.appService = _appService;
}
@Get()
sayHello(){
return this.appService.sayHello();
}
...
}
Postman測試得到一樣的結果
Typescript提供一種complier sugar,可以再簡化程式碼
@Controller()
export class AppController {
// appService: AppService;
// 以private 修飾 appService
// 等同註解掉的程式碼
constructor(
private appService: AppService
// _appService:AppService
){
//this.appService = appService;
}
@Get()
sayHello(){
return this.appService.sayHello();
}
...
}
Providers有三種
明天再繼續