messagebird_async/sms/parameter/
list.rs

1/// Query a list of messages
2///
3/// Still needs some work and the names are garbage
4use super::*;
5
6use hyper;
7
8/// Query Parameters
9///
10/// Filters the results of the query on the backend service side.
11#[derive(Debug, Serialize)]
12#[serde(deny_unknown_fields)]
13pub struct ListParameters {
14    // #[serde(flatten)]
15    originator: Option<Originator>,
16    recipient: Option<QueryRecipient>,
17    // #[serde(flatten)]
18    direction: Option<Direction>,
19    limit: Option<usize>,
20    offset: Option<usize>,
21    #[serde(rename = "searchterm")]
22    searchterms: Vec<String>,
23    // #[serde(flatten)]
24    #[serde(rename = "type")]
25    payload_type: Option<PayloadType>,
26    // #[serde(flatten)]
27    contact_id: Option<Contact>,
28    // #[serde(flatten)]
29    status: Option<Status>,
30    #[serde(flatten)]
31    start: Option<DateTime>,
32    #[serde(flatten)]
33    end: Option<DateTime>,
34}
35
36impl Default for ListParameters {
37    fn default() -> Self {
38        ListParameters {
39            originator: None,
40            recipient: None,
41            direction: None,
42            limit: None,
43            offset: None,
44            searchterms: vec![],
45            payload_type: None,
46            contact_id: None,
47            status: None,
48            start: None,
49            end: None,
50        }
51    }
52}
53
54use std::fmt;
55use std::string::String;
56
57impl fmt::Display for ListParameters {
58    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59        let base = String::from("https://rest.messagebird.com/messages");
60        let query = serde_url_params::to_string(self).unwrap();
61        write!(f, "{}?{}", base, query)
62    }
63}
64
65impl Query for ListParameters {
66    fn uri(&self) -> hyper::Uri {
67        let uri: hyper::Uri = self
68            .to_string()
69            .parse()
70            .expect("Failed to parse list query object to hyper::Uri");
71        uri
72    }
73}
74
75impl ListParameters {
76    /// Construct the `ListParameters` using the builder pattern
77    pub fn builder() -> Builder {
78        Builder::default()
79    }
80}
81
82pub struct Builder(ListParameters);
83
84impl Default for Builder {
85    fn default() -> Self {
86        Builder(ListParameters::default())
87    }
88}
89
90impl Builder {
91    /// Filters for the origin of the message
92    ///
93    /// May be either a phone number, contact (unimplemented as of now) or a string.
94    /// Messages which are sent via the API and do not have an origin defined will have `"inbox"`
95    /// be the default originator.
96    pub fn with_origin(mut self, originator: Originator) -> Self {
97        self.0.originator = Some(originator);
98        self
99    }
100
101    /// Filters for the payload type, either being `SMS` or `Binary`
102    pub fn with_payload_type(mut self, payload_type: PayloadType) -> Self {
103        self.0.payload_type = Some(payload_type);
104        self
105    }
106
107    /// Filters for the direction
108    pub fn with_direction(mut self, direction: Direction) -> Self {
109        self.0.direction = Some(direction);
110        self
111    }
112
113    /// Filters for the status of the messages being listed
114    pub fn with_status(mut self, status: Status) -> Self {
115        self.0.status = Some(status);
116        self
117    }
118
119    /// Counterpart to `with_origin`
120    pub fn with_destination<T>(mut self, msisdn: T) -> Self
121    where
122        T: Into<QueryRecipient>,
123    {
124        self.0.recipient = Some(msisdn.into());
125        self
126    }
127
128    /// The number of messages to skip before listing.
129    /// Allows it to be used as paginating.
130    pub fn skip(mut self, skip: u32) -> Self {
131        self.0.offset = Some(skip as usize);
132        self
133    }
134
135    /// Limits the number of returned messages
136    pub fn count(mut self, upper_limit: u32) -> Self {
137        self.0.limit = Some(upper_limit as usize);
138        self
139    }
140
141    /// Validate the message contained a fixed term
142    pub fn contains_term(mut self, term: &str) -> Self {
143        self.0.searchterms.push(term.to_string());
144        self
145    }
146
147    /// Filters for messages that were sent in a certain range
148    pub fn between(self, start: DateTime, stop: DateTime) -> Self {
149        self.from(start).until(stop)
150    }
151
152    /// Defines the timspan since when the message was sent
153    /// TODO rename, too amibiguous
154    pub fn from(mut self, start: DateTime) -> Self {
155        self.0.start = Some(start);
156        self
157    }
158
159    /// Until what timestamp the messages we are interested in are filtered
160    pub fn until(mut self, stop: DateTime) -> Self {
161        self.0.end = Some(stop);
162        self
163    }
164
165    // TODO contact_id is missing, but that'd require having some kind of
166    // abstraction over that in place
167    /// Finalizes and returns the `ListParameters`
168    pub fn build(self) -> ListParameters {
169        self.0
170    }
171}
172
173// only need one way for this one, ambiguity for recipients makes impl
174// deserialize impossible without knowing all the existing group ids
175// which would imply implementing the group id API
176#[cfg(test)]
177mod tests {
178
179    // helper construct for testing
180    #[derive(Debug, Serialize, Eq, PartialEq)]
181    struct Frame<T> {
182        pub inner: T,
183    }
184
185    use super::*;
186    #[test]
187    fn query_list() {
188        let msisdns: Vec<Msisdn> =
189            vec![Msisdn::new(123475).unwrap(), Msisdn::new(12345677).unwrap()];
190        let url_params = ListParameters::builder()
191            .contains_term("fun")
192            .with_destination(msisdns[0])
193            .build();
194        println!("list obj {:?}", url_params);
195
196        let url_params_str = serde_url_params::to_string(&url_params).unwrap();
197        println!("list params are \"{}\"", url_params_str);
198        assert_eq!(
199            url_params.to_string(),
200            "https://rest.messagebird.com/messages?recipient=123475&searchterm=fun".to_string()
201        );
202    }
203}