蒼時弦也
蒼時弦也
資深軟體工程師
發表於

購物車側欄 - Clean Architecture in TypeScript

這篇文章是 Clean Architecture in TypeScript 系列的一部分,你可以透過 Leanpub 提前閱讀內容。

目前對話功能除了保存紀錄外,已經是處於可以使用的狀態。接下來我們要繼續把購物車的側邊欄介面實現出來,用來呈現商品列表。

更新畫面

基本上只要使用 Sidebar 或者 Right Sidebar 的關鍵字,我們就可以拿到一個堪用的側邊欄介面,因此這次也只需要下達對應的提示即可。

要修改的目標是 src/view/Chat.tsx 跟慣例一樣,使用 Aider 時先將這個檔案加入可以編輯的列表之中。

 1We need a right sidebar to display cart items. The cart is controlled by the assistant, we did not need any controls in the sidebar.
 2
 3## Right Sidebar Component
 4
 5Add a `src/view/Sidebar.tsx` to implement the right sidebar component.
 6
 7- A list of cart items.
 8- The total price of the items in the cart.
 9
10## Cart Item Component
11
12Add a `src/view/CartItem.tsx` to implement the cart item component.
13
14- The product image placeholder
15- The product name
16- The product price
17- The quantity of the product in the cart

基本上不用做太多額外的事情就可以完成,但是購物車的「品項」很多時候都有不同的定義,因此在這邊特別將需要顯示的資訊標注出來。

這是在使用 AI 進行開發過程中需要逐步累積的經驗,以往我們可能會覺得這是「影響不大」的資訊,雖然生成後不影響功能,但就會需要花費更多力氣去要求 AI 修正。

後端整合

因為前面的步驟沒有提供後端的處理方式,預設會使用假資料產生畫面。如果我們最終目標是讓 LLM 透過工具幫我們操作購物車,那麼就需要整合真實的後端。

前一個步驟的假資料放在 src/view/Chat.tsx 裡面,加入成可編輯後,還要將 src/index.tsx 加入進來用於後續註冊新的端點。

除此之外,為了確保實作會貼近我們之前的設計,另外將 src/api/chat.tssrc/controller/chat.ts 兩個檔案使用 Read-only 模式加入進來,這樣就不用依靠提示詳細微調實作。

 1Let's add cart api to get cart items from the server.
 2
 3## Get Cart API
 4
 5Add `src/controller/cart.ts` to implement the cart API.
 6
 7- `GET /:id` - Get cart items by session ID in the chat
 8- Use mock data for now
 9- Reference `src/controller/chat.ts` to implement the Hono RPC style controller
10- Update `src/index.ts` to register the route `/api/cart`
11
12## Cart Client
13
14Add `src/api/cart.ts` to implement the cart client.
15
16- Use `src/api/chat.ts` as a reference
17- Implement `getCart` function to fetch cart items from the server
18- Use Hono RPC style for the client
19
20## View
21
22Update the `src/Chat.tsx` component to replace the mock cart data with the data from the server.

隨著專案的實作越來越完整,我們需要給的指示就會更偏向描述功能的運作,其他的實作細節就可以靠「良好的參考」當作基準,產生更多的功能。

累積經驗

如果是常見的功能開發,大多數時候都能用 LLM 來產生可用的實作。然而在許多真實情境中,我們可能已經形成團隊的慣例、外界大多不會知道的特定知識。

在這個前提下,使用 AI 來輔助開發就會需要一些類似「暖身」的處理,這種處理主要是將原有開發流程中的「特定步驟」歸納出來,以及將「良好示範」設計出來,這樣後續的開發就可以以此為基礎進行,進而有效的減少問題。

到目前為止我們已經實作不少功能,然而使用 npm run tsc --noEmit 大概會跑出許多錯誤,以及使用 React Hook 時,需要採用 useCallback() 等細節都還沒有修正。

這些問題會推遲到比較後面的階段處理,如果要應用在真實的開發情境下,越早處理就越能減少後續 AI 繼續產生有問題實作的狀況,這些東西都會在我們使用 AI 開發過程中慢慢變成「 AI 的開發經驗」而且很難被其他人直接複製,除非是公開的專案。