port-adapter-designer
設計 Port 與 Adapter 模式
直接耦合資料庫、HTTP 客戶端或檔案系統的程式碼會造成測試挑戰並限制靈活性。此技能可協助設計 Port 抽象化和 Adapter 實作,實現六角形架構,使商業邏輯與外部依賴之間能夠清晰分離。
تنزيل ZIP المهارة
رفع في Claude
اذهب إلى Settings → Capabilities → Skills → Upload skill
فعّل وابدأ الاستخدام
اختبرها
استخدام "port-adapter-designer". 設計發送電子郵件通知的 Port
النتيجة المتوقعة:
```rust
#[async_trait]
pub trait EmailPort: Send + Sync {
async fn send(&self, to: &Email, subject: &str, body: &str) -> Result<(), NotificationError>;
}
// 領域錯誤類型
#[derive(Debug)]
pub enum NotificationError {
InvalidAddress(String),
SmtpFailed(String),
RateLimited,
}
```
استخدام "port-adapter-designer". 展示 Stripe 付款的 HTTP Adapter
النتيجة المتوقعة:
```rust
pub struct StripeAdapter {
client: reqwest::Client,
api_key: String,
}
#[async_trait]
impl PaymentPort for StripeAdapter {
async fn charge(&self, amount: Money, card: &Card) -> Result<PaymentId, PaymentError> {
// 帶有正確錯誤映射的實作
}
}
```
التدقيق الأمني
آمنAll static findings are false positives. The skill contains documentation and code examples for hexagonal architecture patterns. The 'external_commands' detections are Rust syntax (not shell backticks), 'network' and 'env_access' patterns are example code (not actual execution), and all 'blocker' and 'obfuscation' alerts are scanner misinterpretations of legitimate Rust code constructs.
الأنماط المكتشفة
درجة الجودة
ماذا يمكنك بناءه
重構資料庫耦合的程式碼
開發人員的應用程式中散落著直接的 sqlx 或 diesel 查詢,並希望使程式碼可測試。此技能可協助設計儲存庫 Port 並建立用於單元測試的 Mock 實作。
設計外部服務整合
團隊需要與支付閘道、電子郵件服務或第三方 API 整合。此技能設計可隱藏實作細節的服務 Port,位於乾淨的非同步介面之後。
學習六角形架構模式
開發人員對 Port/Adapter 架構不熟悉,希望了解如何結構化 Rust 程式碼,以實現領域邏輯與基礎設施之間的清晰分離。
جرّب هذه الموجهات
我需要一個 UserRepository 的 Port 特徵,支援 find_by_id、find_by_email、save、delete 和 list 操作。領域類型是 User、UserId、Email 和 RepositoryError。
展示如何使用 sqlx 搭配 PostgreSQL 連線池來實作 UserRepository Port。包括將 sqlx 錯誤正確轉換為領域 RepositoryError。
建立用於測試的 UserRepository 記憶體內實作。對執行緒安全儲存使用 Arc<Mutex<HashMap>>。
[技能主動啟動] 我注意到您在處理常式中直接使用 sqlx::query。您要我為您的儲存庫模式設計 Port 抽象化,並展示如何用 Adapter 實作嗎?這將使您的程式碼可使用 Mock 實作進行測試。
أفضل الممارسات
- 使用領域類型而非基礎設施類型定義 Port。將領域物件傳入和傳出 Port 方法。
- 在 Adapter 邊界將基礎設施錯誤轉換為領域錯誤。絕不將 sqlx、reqwest 或其他函式庫錯誤洩漏到領域程式碼中。
- 讓 Port 實作 Send + Sync 以相容於 Tokio 等非同步執行期。當需要內部可變性時,使用 Arc<Mutex<T>> 或 RwLock。
تجنب
- 直接將儲存庫結構體傳遞給用例,而非定義可被 Mock 的 Port 特徵。
- 直接從應用程式服務傳回基礎設施錯誤(sqlx::Error、reqwest::Error),而非轉換為領域錯誤。
- 設計鏡像資料庫結構的 Port,而非代表領域概念和操作的 Port。