architect_api/accounts/
trader.rs1use crate::{json_schema_is_string, UserId};
2use serde::{Deserialize, Serialize};
3
4#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
5#[serde(untagged)]
6pub enum TraderIdOrEmail {
7 Id(UserId),
8 Email(String),
9}
10
11impl std::fmt::Display for TraderIdOrEmail {
12 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13 match self {
14 Self::Id(id) => write!(f, "{}", id),
15 Self::Email(email) => write!(f, "{}", email),
16 }
17 }
18}
19
20impl std::str::FromStr for TraderIdOrEmail {
21 type Err = anyhow::Error;
22
23 fn from_str(s: &str) -> Result<Self, Self::Err> {
24 if s.contains('@') {
25 Ok(Self::Email(s.to_string()))
26 } else {
27 Ok(Self::Id(s.parse()?))
28 }
29 }
30}
31
32json_schema_is_string!(TraderIdOrEmail);
33
34#[cfg(test)]
35mod tests {
36 use super::*;
37
38 #[test]
39 fn test_trader_specifier_json() {
40 let id: UserId = "aa0fc734-0da2-4168-8712-4c0b67f01c59".parse().unwrap();
41 let email = "test@example.com".to_string();
42
43 let id_spec = TraderIdOrEmail::Id(id);
45 insta::assert_json_snapshot!(id_spec, @r#""aa0fc734-0da2-4168-8712-4c0b67f01c59""#);
46
47 let id_json = r#""aa0fc734-0da2-4168-8712-4c0b67f01c59""#;
49 let id_deserialized: TraderIdOrEmail = serde_json::from_str(id_json).unwrap();
50 assert_eq!(id_spec, id_deserialized);
51
52 let email_spec = TraderIdOrEmail::Email(email.clone());
54 insta::assert_json_snapshot!(email_spec, @r#""test@example.com""#);
55
56 let email_json = r#""test@example.com""#;
58 let email_as_user_id: UserId = "test@example.com".parse().unwrap();
59 let email_deserialized: TraderIdOrEmail =
60 serde_json::from_str(email_json).unwrap();
61 assert_eq!(TraderIdOrEmail::Id(email_as_user_id), email_deserialized);
62 }
63}