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
use has::Has;
use serde::de::DeserializeOwned;
use serde_json;
use {Result, Error};
use parameters::ApiArguments;
pub static QUANDL_API_URL: &'static str = "https://www.quandl.com/api/v3";
pub trait ApiCall<T: DeserializeOwned + Clone>: Has<ApiArguments> {
fn url(&self) -> String {
let mut url = QUANDL_API_URL.to_string();
if let Some(prefix) = self.fmt_prefix() {
url.push_str(&prefix[..]);
}
if let Some(arguments) = self.fmt_arguments() {
url.push('?');
url.push_str(&arguments[..]);
}
url
}
fn encoded_data(&self) -> Result<Vec<u8>> {
::download::download(self.url())
}
fn send(&self) -> Result<T> {
let json_data = {
match String::from_utf8(try!(self.encoded_data())) {
Ok(json) => json,
Err(e) => { return Err(Error::ParsingFailed(e.to_string())); }
}
};
match serde_json::from_str::<T>(&json_data[..]) {
Ok(data) => Ok(data),
Err(e) => Err(Error::ParsingFailed(e.to_string())),
}
}
fn fmt_prefix(&self) -> Option<String> {
None
}
fn fmt_arguments(&self) -> Option<String> {
None
}
}
impl<'a, T: DeserializeOwned + Clone, A: ApiCall<T>> ApiCall<T> for &'a A {
fn url(&self) -> String {
ApiCall::<T>::url(*self)
}
fn encoded_data(&self) -> Result<Vec<u8>> {
ApiCall::<T>::encoded_data(*self)
}
fn send(&self) -> Result<T> {
ApiCall::<T>::send(*self)
}
fn fmt_prefix(&self) -> Option<String> {
ApiCall::<T>::fmt_prefix(*self)
}
fn fmt_arguments(&self) -> Option<String> {
ApiCall::<T>::fmt_arguments(*self)
}
}
impl<'a, T: DeserializeOwned + Clone, A: ApiCall<T>> ApiCall<T> for &'a mut A {
fn url(&self) -> String {
ApiCall::<T>::url(*self)
}
fn encoded_data(&self) -> Result<Vec<u8>> {
ApiCall::<T>::encoded_data(*self)
}
fn send(&self) -> Result<T> {
ApiCall::<T>::send(*self)
}
fn fmt_prefix(&self) -> Option<String> {
ApiCall::<T>::fmt_prefix(*self)
}
fn fmt_arguments(&self) -> Option<String> {
ApiCall::<T>::fmt_arguments(*self)
}
}