use async_trait::async_trait; use chrono::{DateTime, Utc}; use sqlx::PgPool; use domain::{errors::DomainError, models::api_key::ApiKey, ports::ApiKeyRepository, value_objects::{ApiKeyId, UserId}}; pub struct PgApiKeyRepository { pool: PgPool } impl PgApiKeyRepository { pub fn new(pool: PgPool) -> Self { Self { pool } } } #[async_trait] impl ApiKeyRepository for PgApiKeyRepository { async fn save(&self, k: &ApiKey) -> Result<(), DomainError> { sqlx::query("INSERT INTO api_keys(id,user_id,key_hash,name,created_at) VALUES($1,$2,$3,$4,$5)") .bind(k.id.as_uuid()).bind(k.user_id.as_uuid()).bind(&k.key_hash).bind(&k.name).bind(k.created_at) .execute(&self.pool).await.map_err(|e| DomainError::Internal(e.to_string())).map(|_| ()) } async fn find_by_hash(&self, hash: &str) -> Result, DomainError> { #[derive(sqlx::FromRow)] struct Row { id: uuid::Uuid, user_id: uuid::Uuid, key_hash: String, name: String, created_at: DateTime } sqlx::query_as::<_, Row>("SELECT id,user_id,key_hash,name,created_at FROM api_keys WHERE key_hash=$1") .bind(hash).fetch_optional(&self.pool).await .map_err(|e| DomainError::Internal(e.to_string())) .map(|o| o.map(|r| ApiKey { id: ApiKeyId::from_uuid(r.id), user_id: UserId::from_uuid(r.user_id), key_hash: r.key_hash, name: r.name, created_at: r.created_at })) } async fn list_for_user(&self, user_id: &UserId) -> Result, DomainError> { #[derive(sqlx::FromRow)] struct Row { id: uuid::Uuid, user_id: uuid::Uuid, key_hash: String, name: String, created_at: DateTime } sqlx::query_as::<_, Row>("SELECT id,user_id,key_hash,name,created_at FROM api_keys WHERE user_id=$1 ORDER BY created_at DESC") .bind(user_id.as_uuid()).fetch_all(&self.pool).await .map_err(|e| DomainError::Internal(e.to_string())) .map(|rows| rows.into_iter().map(|r| ApiKey { id: ApiKeyId::from_uuid(r.id), user_id: UserId::from_uuid(r.user_id), key_hash: r.key_hash, name: r.name, created_at: r.created_at }).collect()) } async fn delete(&self, id: &ApiKeyId, user_id: &UserId) -> Result<(), DomainError> { sqlx::query("DELETE FROM api_keys WHERE id=$1 AND user_id=$2") .bind(id.as_uuid()).bind(user_id.as_uuid()) .execute(&self.pool).await.map_err(|e| DomainError::Internal(e.to_string())).map(|_| ()) } } #[cfg(test)] mod tests { use super::*; use chrono::Utc; use domain::{models::user::User, value_objects::*}; use crate::user::PgUserRepository; use domain::ports::UserRepository; async fn seed_user(pool: &sqlx::PgPool) -> User { let repo = PgUserRepository::new(pool.clone()); let u = User::new_local(UserId::new(), Username::new("alice").unwrap(), Email::new("alice@ex.com").unwrap(), PasswordHash("h".into())); repo.save(&u).await.unwrap(); u } #[sqlx::test(migrations = "./migrations")] async fn save_and_find_by_hash(pool: sqlx::PgPool) { let user = seed_user(&pool).await; let repo = PgApiKeyRepository::new(pool); let key = ApiKey { id: ApiKeyId::new(), user_id: user.id.clone(), key_hash: "abc123".into(), name: "test".into(), created_at: Utc::now() }; repo.save(&key).await.unwrap(); let found = repo.find_by_hash("abc123").await.unwrap().unwrap(); assert_eq!(found.name, "test"); } #[sqlx::test(migrations = "./migrations")] async fn delete_key(pool: sqlx::PgPool) { let user = seed_user(&pool).await; let repo = PgApiKeyRepository::new(pool); let key = ApiKey { id: ApiKeyId::new(), user_id: user.id.clone(), key_hash: "def456".into(), name: "key2".into(), created_at: Utc::now() }; repo.save(&key).await.unwrap(); repo.delete(&key.id, &user.id).await.unwrap(); assert!(repo.find_by_hash("def456").await.unwrap().is_none()); } }