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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{self, Value};
use reqwest::{StatusCode, Response};
use error::ApiResponseError;
use std::io::Read;

#[derive(Debug, Serialize, Deserialize)]
#[allow(non_snake_case)]
pub struct ListMeta {
  pub totalCount: i32,
  pub limit: i32,
  pub nextCursor: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct ListResponse<T: Serialize> {
  pub meta: Option<ListMeta>,
  pub elements: Vec<T>,
}

#[allow(non_snake_case)]
impl<T: Serialize> ListResponse<T> {
  pub fn get_next_cursor(&self) -> Option<&str> {
    match *self {
      ListResponse { meta: Some(ListMeta { nextCursor: Some(ref cursor), .. }), .. } => {
        Some(&cursor)
      }
      _ => None,
    }
  }

  pub fn get_total_count(&self) -> Option<i32> {
    match *self {
      ListResponse { meta: Some(ListMeta { totalCount, .. }), .. } => Some(totalCount),
      _ => None,
    }
  }
}

pub type Result<T> = ::std::result::Result<T, ApiResponseError>;

pub trait JsonMaybe {
  fn json_maybe<T: DeserializeOwned>(&mut self) -> Result<T>;
}

impl JsonMaybe for Response {
  fn json_maybe<T: DeserializeOwned>(&mut self) -> Result<T> {
    let status = self.status();

    let mut body = String::new();
    match self.read_to_string(&mut body) {
      Err(err) => {
        return Err(ApiResponseError {
          status: status.clone(),
          message: format!("read response: {}", err),
          body: "".to_owned(),
        });
      }
      _ => {}
    }

    if !status.is_success() {
      return Err(ApiResponseError {
        message: format!("status not ok: {}", status),
        status: status.clone(),
        body: body,
      });
    }

    match serde_json::from_str::<T>(&body) {
      Ok(v) => {
        return Ok(v);
      }
      Err(err) => {
        return Err(ApiResponseError {
          message: format!("deserialize body: {}", err),
          status: status.clone(),
          body: body,
        });
      }
    }
  }
}

/// Get `meta` and `elements` from a JSON API response
pub fn parse_list_elements_json<T, R>(
  status: StatusCode,
  reader: &mut R,
  key: &str,
) -> Result<ListResponse<T>>
where
  T: Serialize + DeserializeOwned,
  R: Read,
{
  use std::collections::BTreeMap;

  #[derive(Debug, Deserialize)]
  pub struct Inner {
    pub meta: ListMeta,
    pub elements: BTreeMap<String, Value>,
  }

  #[derive(Debug, Deserialize)]
  pub struct Response {
    pub list: Inner,
  }

  if status == StatusCode::NotFound {
    return Ok(ListResponse {
      meta: None,
      elements: vec![],
    });
  }

  let mut body = String::new();
  match reader.read_to_string(&mut body) {
    _ => {}
  }

  if !status.is_success() {
    return Err(ApiResponseError {
      message: status.to_string(),
      status: status.clone(),
      body: body,
    });
  }

  match serde_json::from_str::<Response>(&body) {
    Ok(mut res) => {
      let value = match res.list.elements.remove(key) {
        Some(value) => value,
        None => {
          return Err(ApiResponseError {
            message: format!("key '{}' was not found in resposne", key),
            status: status.clone(),
            body: body,
          });
        }
      };

      match serde_json::from_value::<Vec<T>>(value) {
        Ok(elements) => {
          return Ok(ListResponse {
            meta: res.list.meta.into(),
            elements: elements,
          });
        }
        Err(err) => {
          return Err(ApiResponseError {
            message: format!("deserialize json response elements: {}", err.to_string()),
            status: status.clone(),
            body: body,
          });
        }
      }
    }
    Err(err) => {
      return Err(ApiResponseError {
        message: format!("deserialize json response: {}", err.to_string()),
        status: status.clone(),
        body: body,
      });
    }
  }
}

/// Get single object from a JSON API response
pub fn parse_object_json<T, R>(status: StatusCode, reader: &mut R, key: &str) -> Result<T>
where
  T: Serialize + DeserializeOwned,
  R: Read,
{
  use std::collections::BTreeMap;

  let mut body = String::new();
  match reader.read_to_string(&mut body) {
    _ => {}
  }

  if !status.is_success() {
    return Err(ApiResponseError {
      message: status.to_string(),
      status: status.clone(),
      body: body,
    });
  }

  match serde_json::from_str::<BTreeMap<String, T>>(&body) {
    Ok(mut obj) => {
      match obj.remove(key) {
        Some(value) => {
          return Ok(value);
        }
        None => {
          return Err(ApiResponseError {
            message: format!("key '{}' was not found in resposne", key),
            status: status.clone(),
            body: body,
          });
        }
      }
    }
    Err(err) => {
      return Err(ApiResponseError {
        message: format!("deserialize json response: {}", err.to_string()),
        status: status.clone(),
        body: body,
      });
    }
  }
}

#[cfg(test)]
mod test {
  use super::*;
  use std::io::Cursor;

  #[test]
  fn test_parse_list_elements_json() {
    use order::Order;
    let mut r = Cursor::new(include_str!("./order/test_order_list_res.json").to_string());
    let res = parse_list_elements_json::<Order, _>(StatusCode::Ok, &mut r, "order").unwrap();
    let meta = res.meta.unwrap();
    assert_eq!(meta.totalCount, 66);
    assert_eq!(meta.limit, 10);
    assert_eq!(res.elements.len(), 2);
  }

  #[test]
  fn test_parse_object_json() {
    use order::Order;
    let mut r = Cursor::new(include_str!("./order/test_order.json").to_string());
    let res = parse_object_json::<Order, _>(StatusCode::Ok, &mut r, "order").unwrap();
    assert_eq!(res.shippingInfo.estimatedDeliveryDate, 1485586800000);
  }
}