用 Nest.js 開發 API 吧 (四) - Service


Posted by AlanSyue on 2020-12-13

上一篇介紹了 Nest.js 中 Controller 的使用方式,這次要來介紹 Service 的用法。
之前有提到:

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

因此當 Controller 接收到請求後,會呼叫 Service 進行商業邏輯的操作,再回應給 Client。

讓我們來看以下程式碼範例:

一、在 module 注入 AppService

/src/app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

二、在 controller 呼叫 service 方法

在 controller 建構子(constructor) 引入 AppService:

private readonly appService: AppService

然後去呼叫 getHello 方法

/src/app.controller.ts

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();
  }
}

三、在 service 撰寫商業邏輯

在 AppService 撰寫 getHello 的 function,並回傳 Hello World
/src/app.service.ts

import { Injectable } from '@nestjs/common';

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

四、實際呼叫 API

用 Postman 去呼叫 http://localhost:3000,就會獲得 Hello World 字串。

小結

今天介紹了如果從 Controller 引入 Service 使用,下次會分享 Nest.js 如何搭配 TypeOrm 來實作 CRUD,如果文章有任何錯誤或建議,歡迎告知!

NEXT:用 Nest.js 開發 API 吧 (五) - Postgresql


#nestjs #nodejs #API #javascript #service







Related Posts

AI輔導室|製作相扣的紙花圈

AI輔導室|製作相扣的紙花圈

用 Nest.js 開發 API 吧 (四) - Service

用 Nest.js 開發 API 吧 (四) - Service

瀏覽器渲染流程

瀏覽器渲染流程


Comments