iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 19
0
自我挑戰組

從零開始的後端異世界生活系列 第 19

Day 19 - 把商業邏輯拆分至 NestJS 的 Service 層中

創建 Service Module

在上一篇章時,我們已經完成了範例的 DB 資料表創建,接下來我們先來建立個 Service 層,好為之後要撰寫商業邏輯做準備,那我們先輸入以下 CLI 做 Service Module 的建立:

nest g module services

OK,建立完畢,AppModule 也順便幫我們一起引入了 ServicesModule:
https://ithelp.ithome.com.tw/upload/images/20201004/20119619kItjPBeqlt.png

https://ithelp.ithome.com.tw/upload/images/20201004/20119619dEwQcVJlLO.png

再來,我們在 Services 資料夾裡面來建立有關「Tasks」這個功能模組的 Service,輸入以下 CLI 進行建立:

nest g service services/tasks

OK,建立完畢,ServicesModule 也順便一起幫我們把 TasksService 放到 imports 了:
https://ithelp.ithome.com.tw/upload/images/20201004/20119619184vhCpUgI.png

https://ithelp.ithome.com.tw/upload/images/20201004/201196191YLN55Uxy0.png

搬遷商業邏輯至 Service 層

我們已經建立好 TasksService,那現在該把 TasksController 裡的邏輯搬遷至 Service 層了(雖然還沒有寫邏輯就是了 XD),先拿個範例來講解,目前這個 GET 方法長這樣:
https://ithelp.ithome.com.tw/upload/images/20201004/201196199jJLm2Woym.png

那我們先在 Controller 上面使用依賴注入,將 TasksService 注入到這個 Controller:
https://ithelp.ithome.com.tw/upload/images/20201004/20119619UG6Nv9NzpM.png

然後在 TasksService 裡撰寫自己想要的商業邏輯(先隨便寫寫):
https://ithelp.ithome.com.tw/upload/images/20201004/201196194rDd4a0wkE.png

再由剛剛那個 GET 方法去呼叫它:
https://ithelp.ithome.com.tw/upload/images/20201004/20119619YNmoY8HfwQ.png

好,我們現在試著運行 Server 看看,然後就炸裂了:
https://ithelp.ithome.com.tw/upload/images/20201004/2011961904yfkyLyqX.png

原來是我忘記在 Controller 的 Module 將 ServicesModule 給引入,那先把它給補上:
https://ithelp.ithome.com.tw/upload/images/20201004/20119619Iduhqk0ADs.png

還是炸裂拉:
https://ithelp.ithome.com.tw/upload/images/20201004/201196199UTUnlXOKc.png

突然想到,我應該要在 ServicesModule 中把 TasksService 給 exports 出去,別人才拿得到它:
https://ithelp.ithome.com.tw/upload/images/20201004/201196192X9nq6pIrQ.png

OK,痛哭流涕,終於完成了分離 Service 層的工作。
https://ithelp.ithome.com.tw/upload/images/20201004/20119619lSpvUiSFLD.png

下一篇章

下一篇章我們來把 Repository 注入到 Service 中使用。

/*
本系列文係個人新手開發心得,可能會有許多錯誤,煩請多多包容不吝指教。
*/


上一篇
Day 18 - 使用指令同步 DB 資料表來生成 Entity(下)
下一篇
Day 20 - 把 Repository<Entity> 注入到 Service 中並使用它
系列文
從零開始的後端異世界生活30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言