---
title: "購物車側欄 - Clean Architecture in TypeScript"
date: 2025-09-26T00:00:00+08:00
publishDate: 2025-09-26T00:00:00+08:00
lastmod: 2025-11-21T10:38:12+08:00
tags: ["TypeScript","Clean Architecture","架構","經驗","AI"]
series: "clean-architecture-in-ts"
toc: true
permalink: "https://blog.aotoki.me/posts/2025/09/26/clean-architecture-in-ts-shopping-cart-sidebar/"
language: "zh-tw"
---



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

<!--more-->

## 更新畫面{#update-view}

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

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

```markdown
We need a right sidebar to display cart items. The cart is controlled by the assistant, we did not need any controls in the sidebar.

## Right Sidebar Component

Add a `src/view/Sidebar.tsx` to implement the right sidebar component.

- A list of cart items.
- The total price of the items in the cart.

## Cart Item Component

Add a `src/view/CartItem.tsx` to implement the cart item component.

- The product image placeholder
- The product name
- The product price
- The quantity of the product in the cart
```

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

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

## 後端整合{#backend-api}

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

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

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

```markdown
Let's add cart api to get cart items from the server.

## Get Cart API

Add `src/controller/cart.ts` to implement the cart API.

- `GET /:id` - Get cart items by session ID in the chat
- Use mock data for now
- Reference `src/controller/chat.ts` to implement the Hono RPC style controller
- Update `src/index.ts` to register the route `/api/cart`

## Cart Client

Add `src/api/cart.ts` to implement the cart client.

- Use `src/api/chat.ts` as a reference
- Implement `getCart` function to fetch cart items from the server
- Use Hono RPC style for the client

## View

Update the `src/Chat.tsx` component to replace the mock cart data with the data from the server.
```

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

## 累積經驗{#gain-experience}

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

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

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

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