use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::domain; #[derive(Debug, Clone, Deserialize)] pub struct AccountMemberRequest { pub user: UserRequest, } impl AccountMemberRequest { pub fn into_domain( self, id: Uuid, account_id: Uuid, ) -> Result { Ok(domain::AccountMember { id, account_id, user_id: self.user.id, }) } } #[derive(Debug, Clone, Deserialize)] pub struct UserRequest { pub id: Uuid, } #[derive(Debug, Clone, Serialize)] pub struct AccountMemberResponse { pub id: Uuid, pub user: UserResponse, } impl From for AccountMemberResponse { fn from(member: domain::AccountMember) -> Self { Self { id: member.id, user: UserResponse { id: member.user_id }, } } } #[derive(Debug, Clone, Serialize)] pub struct UserResponse { pub id: Uuid, } #[cfg(test)] mod tests { use super::*; fn request(user_id: Uuid) -> AccountMemberRequest { AccountMemberRequest { user: UserRequest { id: user_id }, } } #[test] fn serializes_account_member_response() { let id = Uuid::new_v4(); let member = request(Uuid::nil()) .into_domain(id, Uuid::new_v4()) .unwrap(); let response = serde_json::to_value(AccountMemberResponse::from(member)).unwrap(); assert_eq!(response["id"], id.to_string()); assert_eq!(response["user"]["id"], Uuid::nil().to_string()); assert!(response.get("account_id").is_none()); } #[test] fn deserializes_account_member_response_as_request() { let member = request(Uuid::nil()) .into_domain(Uuid::new_v4(), Uuid::new_v4()) .unwrap(); let response = serde_json::to_value(AccountMemberResponse::from(member)).unwrap(); let request: AccountMemberRequest = serde_json::from_value(response).unwrap(); assert_eq!(request.user.id, Uuid::nil()); } #[test] fn converts_between_dto_and_domain() { let id = Uuid::new_v4(); let account_id = Uuid::new_v4(); let user_id = Uuid::new_v4(); let member = request(user_id).into_domain(id, account_id).unwrap(); assert_eq!(member.id, id); assert_eq!(member.account_id, account_id); assert_eq!(member.user_id, user_id); let response = AccountMemberResponse::from(member); assert_eq!(response.id, id); assert_eq!(response.user.id, user_id); } }