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

Alan Syue
Dec 13, 2020

Nest.js 官方網站

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

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

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

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

一、在 module 注入 AppService

/src/app.module.ts

二、在 controller 呼叫 service 方法

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

private readonly appService: AppService

然後去呼叫 getHello 方法

/src/app.controller.ts

三、在 service 撰寫商業邏輯

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

四、實際呼叫 API

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

小結

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

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Alan Syue
Alan Syue

Written by Alan Syue

Backend Engineer at UPN | Love to share everything

No responses yet

Write a response