mailjet_rs/api/common/
recipient.rs1use serde::{Deserialize, Serialize};
2use std::fmt::Write;
3
4pub type Recipients = Vec<Recipient>;
6
7#[derive(Debug, Serialize, Deserialize)]
10pub struct Recipient {
11 #[serde(rename = "Email")]
12 pub email: String,
13 #[serde(rename = "Name")]
14 pub name: String,
15}
16
17impl Recipient {
18 pub fn new(email: &str) -> Self {
20 Self {
21 email: String::from(email),
22 name: String::default(),
23 }
24 }
25
26 pub fn with_name(email: &str, name: &str) -> Self {
29 Self {
30 email: String::from(email),
31 name: String::from(name),
32 }
33 }
34
35 pub fn from_comma_separated(recipients: &str) -> Vec<Self> {
40 let as_string_vec = recipients.split(',');
41
42 as_string_vec
43 .into_iter()
44 .map(Recipient::new)
45 .collect::<Vec<Recipient>>()
46 }
47
48 pub fn as_comma_separated(&self) -> String {
54 let mut string = String::default();
55
56 if !self.name.is_empty() {
57 let _ = write!(string, "\"{}\"", self.name);
58 string += " ";
59 }
60
61 let _ = write!(string, "<{}>", self.email);
62 string
63 }
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69
70 #[test]
71 fn creates_recipient_from_comma_separated() {
72 let have = "foo@bar.com,rust@rust-lang.org,hyper_rs.alpha@gmail.com";
73 let want = vec![
74 Recipient::new("foo@bar.com"),
75 Recipient::new("rust@rust-lang.org"),
76 Recipient::new("hyper_rs.alpha@gmail.com"),
77 ];
78
79 for (index, recipient) in have.split(',').enumerate().into_iter() {
80 assert_eq!(recipient.to_string(), want.get(index).unwrap().email);
81 }
82 }
83
84 #[test]
85 fn creates_comma_separated_from_recipient() {
86 let have = vec![
87 Recipient::with_name("rust@rust-lang.org", "The Rust Programming Language"),
88 Recipient::new("foo@bar.com"),
89 ];
90 let want = vec![
91 String::from("\"The Rust Programming Language\" <rust@rust-lang.org>"),
92 String::from("<foo@bar.com>"),
93 ];
94
95 have.into_iter().enumerate().for_each(|(index, value)| {
96 assert_eq!(
97 value.as_comma_separated().as_str(),
98 want.get(index).unwrap()
99 );
100 })
101 }
102}