1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
use reqwest::{Client as HttpClient, RequestBuilder, StatusCode, Url}; use types::{DateTime, Utc}; use error::*; pub use reqwest::Method; use serde::Deserialize; mod types; pub use self::types::*; #[doc(hidden)] #[macro_export] macro_rules! shopify_wrap { ( pub struct $t:ident { $key:ident: $inner_t:ty$(,)* } ) => { use client::ShopifyWarpper; #[derive(Debug, Deserialize)] pub struct $t { $key: $inner_t, } impl ShopifyWarpper<$inner_t> for $t { fn into_inner(self) -> $inner_t { self.$key } } } } pub(crate) trait AsQueryValue { fn as_query_value(&self) -> String; } macro_rules! impl_into_query_value { ( $t:ty ) => ( impl AsQueryValue for $t { fn as_query_value(&self) -> String { format!("{}", self) } } ); ( $t:ty, $f:expr ) => ( impl AsQueryValue for $t { fn as_query_value(&self) -> String { $f(self) } } ); } impl_into_query_value!(i64); impl_into_query_value!(String); impl_into_query_value!(DateTime<Utc>, |date: &DateTime<Utc>| date.to_rfc3339()); impl<T> AsQueryValue for Vec<T> where T: AsQueryValue, { fn as_query_value(&self) -> String { self .iter() .map(|v| v.as_query_value()) .collect::<Vec<_>>() .join(",") } } #[doc(hidden)] #[macro_export] macro_rules! request_query { ( pub struct $t:ident { $(pub $key:ident: Option<$field_t:ty>),* $(,)* } ) => ( use client::{ShopifyRequestQuery, AsQueryValue}; #[derive(Debug, Default)] pub struct $t { $( pub $key: Option<$field_t> ),* } impl ShopifyRequestQuery for $t { fn as_query_pairs(&self) -> Vec<(String, String)> { let mut pairs = vec![]; $( request_query!(PUSH_FIELD self, pairs, $key, $field_t); )* pairs } } ); (PUSH_FIELD $s:expr, $v:expr, $key:ident, $t:tt) => { if let Some(ref v) = $s.$key { $v.push(( stringify!($key).to_owned(), v.as_query_value(), )); } }; } #[derive(Debug, Clone)] pub struct Client { base_url: Url, api_key: String, password: String, client: HttpClient, } impl Client { pub fn new(base_url: &str, api_key: &str, password: &str) -> Result<Self> { Ok(Client { base_url: Url::parse(base_url)?, api_key: api_key.to_owned(), password: password.to_owned(), client: HttpClient::new(), }) } pub fn with_http_client( client: HttpClient, base_url: &str, api_key: &str, password: &str, ) -> Result<Self> { Ok(Client { base_url: Url::parse(base_url)?, api_key: api_key.to_owned(), password: password.to_owned(), client: client, }) } pub fn request_with_params<P, T, F>( &self, method: Method, path: &str, params: &P, bf: F, ) -> Result<T> where P: ShopifyRequestQuery, T: for<'de> Deserialize<'de>, F: FnOnce(&mut RequestBuilder), { let mut url = self.base_url.join(path)?; url.query_pairs_mut().extend_pairs(params.as_query_pairs()); let mut b = self.client.request(method, url); b.basic_auth(self.api_key.clone(), Some(self.password.clone())); bf(&mut b); let mut res = b.send()?; if !res.status().is_success() { if res.status() == StatusCode::NotFound { return Err(ErrorKind::NotFound.into()); } let body = res.text()?; return Err(ErrorKind::Request(path.to_owned(), res.status(), body).into()); } res.json().chain_err(|| ErrorKind::InvalidResponse) } pub fn request<T, F>(&self, method: Method, path: &str, bf: F) -> Result<T> where T: for<'de> Deserialize<'de>, F: FnOnce(&mut RequestBuilder), { self.request_with_params(method, path, &(), bf) } } #[cfg(test)] pub fn get_test_client() -> Client { use std::env::var; ::dotenv::dotenv().ok(); Client::new( &var("SHOPIFY_BASE_URL").unwrap(), &var("SHOPIFY_API_KEY").unwrap(), &var("SHOPIFY_PASSWORD").unwrap(), ).unwrap() }