iT邦幫忙

2025 iThome 鐵人賽

DAY 20
0
自我挑戰組

跟 AI Agent 變成好朋友系列 第 20

【Day20】AI Agent 魔法詠唱 - 建立 DTO

  • 分享至 

  • xImage
  •  

而DTO(Data Transfer Object)是一種用於在不同系統或層之間傳遞資料的物件,常見於 API 的輸入與輸出。DTO 的主要目的是將資料結構與類別邏輯(Entity)分離,避免直接暴露資料庫結構,提升安全性、靈活性與維護性。

以 RecommendationResponse 為例,這個類別用於回應前端關於飲品推薦的 API 請求。它封裝了使用者輸入、偵測到的心情、AI 推薦結果、推薦理由、推薦飲品清單、回應時間、狀態、訊息、服務類型等資訊。這些欄位都是 API 回傳給前端所需的資料,並不直接對應資料庫的 Entity 結構。

程式碼範例:

public class RecommendationResponse {
    private String userInput; // 使用者輸入
    private String moodDetected; // 偵測到的心情
    private String aiResponse; // AI 回覆
    private String aiReason; // AI 推薦理由
    private List<DrinkRecommendation> recommendations; // 飲品推薦清單
    private LocalDateTime timestamp; // 回應時間
    private String status; // 狀態(success/error)
    private String message; // 訊息
    private String serviceType; // 服務類型(如 AWS Bedrock)
    private boolean isBedrockAvailable; // Bedrock 是否可用

    // ...建構子、getter/setter、錯誤回應工廠方法...
}

DTO 是 API 設計的重要工具,能有效隔離資料層與任務邏輯,提升系統安全性與可維護性。

像是RecommendationResponse用於完整初始化推薦回應物件,選用了使用者輸入、偵測到的心情、AI 推薦結果、推薦理由、推薦飲品清單、服務類型以及確認Bedrock 是否可用等欄位。
先呼叫無參數建構子,確保預設狀態已設定,再依需求填入各欄位。

		public RecommendationResponse(String userInput, String moodDetected, String aiResponse, String aiReason, List<DrinkRecommendation> recommendations, String serviceType, boolean isBedrockAvailable) {
        this();
        this.userInput = userInput;
        this.moodDetected = moodDetected;
        this.aiResponse = aiResponse;
        this.aiReason = aiReason;
        this.recommendations = recommendations;
        this.serviceType = serviceType;
        this.isBedrockAvailable = isBedrockAvailable;
    }
    
    public static RecommendationResponse error(String message) {
        RecommendationResponse response = new RecommendationResponse();
        response.status = "error";
        response.message = message;
        return response;
    }

亦可用於快速建立錯誤回應物件,讓回應物件的狀態設為 "error",並填入錯誤訊息,而其他欄位依然維持預設值。這樣的方式能夠便於 API 在發生例外或錯誤時,統一回傳標準格式的錯誤訊息給前端。並根據實際需求彈性擴充欄位,提升 API 的可維護性與一致性。


上一篇
【Day19】AI Agent 魔法詠唱 - 建立 Repository
下一篇
【Day21】AI Agent 魔法詠唱 - 建立 Service
系列文
跟 AI Agent 變成好朋友22
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言