iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 20
0
自我挑戰組

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

Day 20 - 把 Repository<Entity> 注入到 Service 中並使用它

  • 分享至 

  • twitterImage
  •  

將 Repository 注入 Service

在上一篇章的時候,我們完成了 Service 層的拆分,今天我們來把前幾天完成的 Task 資料表,利用 Repository 注入到 TasksService 中並試著撰寫一些操作 DB 的邏輯。

首先我們來到 ServicesModule,在 imports 的部分寫下:
https://ithelp.ithome.com.tw/upload/images/20201005/201196199wz5a2M8Vg.png

然後我們再到 TasksService 中,使用 constructor 將 Repository 給注入:
https://ithelp.ithome.com.tw/upload/images/20201005/20119619IVQoXlLTqP.png

完成後我們試著運行 Server 看看,啊呀,有錯誤呢:
https://ithelp.ithome.com.tw/upload/images/20201005/20119619pstwoxLdun.png

我們到 typeOrmConfig 中,把 Task 放到 entities 中,順便把 synchronize 取消掉:
https://ithelp.ithome.com.tw/upload/images/20201005/201196199CSEOEQJl8.png

好了,看起來沒問題了:
https://ithelp.ithome.com.tw/upload/images/20201005/20119619Na4rlGFXuR.png

撰寫 新增任務資訊 API

首先我們先來撰寫第一支 API - 新增任務資訊,我們先來到 TasksInfoDTO,目前是長這樣:
https://ithelp.ithome.com.tw/upload/images/20201005/20119619HuP5u9Xt1a.png

我們來修改一下,讓它跟資料庫的要求一樣:
https://ithelp.ithome.com.tw/upload/images/20201005/20119619SsymHzUtLE.png

之後我們新增一個基本的 Task 回傳:
https://ithelp.ithome.com.tw/upload/images/20201005/20119619xY66gUiN0v.png

再來到 TasksService 中寫下一支非同步的 Function,並把 Body 的參數給帶進來:
https://ithelp.ithome.com.tw/upload/images/20201005/201196194574nQSnNP.png

然後我們在此支 Function 中撰寫對任務的新增(這邊時間有引入 luxon 庫):
https://ithelp.ithome.com.tw/upload/images/20201005/20119619HZzkyHyUGL.png

之後將新增的這筆資料給存起來,然後當作回傳:
https://ithelp.ithome.com.tw/upload/images/20201005/20119619rZ3r12kKah.png

再到 TasksController 修改一點點代碼:
https://ithelp.ithome.com.tw/upload/images/20201005/20119619wlpm2IUOUY.png

好了,讓我們運行 Server,試著打打看這支 Post 的 API 吧。

在參數這邊我先隨意輸入:
https://ithelp.ithome.com.tw/upload/images/20201005/20119619U1D4ykkwh3.png

然後按下送出,耶,順利得到回應拉:
https://ithelp.ithome.com.tw/upload/images/20201005/20119619uQwLrwusHm.png

資料庫裡也確實建立了這筆資料:
https://ithelp.ithome.com.tw/upload/images/20201005/20119619uyKOW9NdGk.png

OK,這樣超簡易版的 CRUD 中的 C 總算是完成了~但還缺乏很多錯誤處理及統一回傳之類的問題,我們後續篇章繼續修改~

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


上一篇
Day 19 - 把商業邏輯拆分至 NestJS 的 Service 層中
下一篇
Day 21 - 新增 User Entity 並增加與 Task 之 Database Relation
系列文
從零開始的後端異世界生活30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言