twilio_async/
macros.rs

1macro_rules! execute {
2    ($ty:tt) => {
3        #[async_trait]
4        impl<'a> Execute for $ty<'a> {
5            fn request<U>(
6                &self,
7                method: Method,
8                url: U,
9                body: Option<String>,
10            ) -> Result<hyper::Request<hyper::Body>, TwilioErr>
11            where
12                U: AsRef<str>,
13            {
14                use hyper::{
15                    header::{HeaderMap, HeaderValue, CONTENT_TYPE},
16                    Request,
17                };
18                use typed_headers::HeaderMapExt;
19                const BASE: &str = "https://api.twilio.com/2010-04-01/Accounts";
20
21                let url = format!("{}/{}/{}", BASE, self.client.sid, url.as_ref())
22                    .parse::<hyper::Uri>()?;
23                let mut request = Request::builder().method(method).uri(url);
24
25                let mut hmap = HeaderMap::new();
26                hmap.typed_insert(&self.client.auth);
27                for (k, v) in hmap {
28                    request = request.header(k.unwrap().as_str(), v);
29                }
30                Ok(match body {
31                    Some(body) => request
32                        .header(
33                            CONTENT_TYPE,
34                            HeaderValue::from_static("application/x-www-form-urlencoded"),
35                        )
36                        .body(hyper::Body::from(body))?,
37                    None => request.body(hyper::Body::empty())?,
38                })
39            }
40
41            async fn execute<U, D>(
42                &self,
43                method: Method,
44                url: U,
45                body: Option<String>,
46            ) -> TwilioResp<crate::TwilioJson<D>>
47            where
48                U: AsRef<str> + Send,
49                D: for<'de> serde::Deserialize<'de>,
50            {
51                use bytes::Buf;
52                use serde_json;
53
54                let req = self.request(method, url, body)?;
55
56                let res = self
57                    .client
58                    .client
59                    .request(req)
60                    .await
61                    .map_err(TwilioErr::NetworkErr)?;
62
63                let body = hyper::body::aggregate(res).await?;
64
65                let json_resp = serde_json::from_reader(body.reader())?;
66                Ok(json_resp)
67            }
68        }
69    };
70}
71
72macro_rules! from {
73    ($x:ty, $variant:ident) => {
74        impl From<$x> for TwilioErr {
75            fn from(e: $x) -> Self {
76                $variant(e)
77            }
78        }
79    };
80}
81
82macro_rules! pair {
83    ($x:ident, $field:ident, $name:tt, $vec:ident) => {
84        if let Some($field) = $x.$field {
85            $vec.push(($name, $field));
86        }
87    };
88}