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
extern crate reqwest;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use serde::de::DeserializeOwned;
use std::marker::PhantomData;
mod date_format;
pub mod model;
const BASE_URL: &str = "http://musicbrainz.org/ws/2";
pub struct Query<T, I: Include<T>> {
path: String,
include: Vec<I>,
phantom: PhantomData<T>,
}
impl<'a, T, I> Query<T, I>
where
I: Include<T> + PartialEq,
{
pub fn execute(&mut self) -> Result<T, reqwest::Error>
where
T: QueryAble<'a, I> + DeserializeOwned,
{
let client = reqwest::Client::new();
self.path.push_str("?fmt=json");
self.include_to_path();
client.get(&self.path).send()?.json()
}
pub fn include(&mut self, include: I) -> &mut Self {
self.include.push(include);
self
}
pub fn id(&mut self, id: &str) -> &mut Self {
self.path.push_str(&format!("/{}", id));
self
}
fn include_to_path(&mut self) {
if !self.include.is_empty() {
self.path.push_str("&inc=");
}
for inc in self.include.iter() {
if Some(inc) != self.include.last() {
self.path.push_str(inc.as_str());
self.path.push_str("+");
} else {
self.path.push_str(inc.as_str());
}
}
}
}
pub trait QueryAble<'a, I> {
fn path() -> &'static str;
fn fetch() -> Query<Self, I>
where
Self: Sized,
I: Include<Self> + PartialEq,
{
Query {
path: format!("{}/{}", BASE_URL, Self::path()),
phantom: PhantomData,
include: vec![],
}
}
}
pub trait Include<T> {
fn as_str(&self) -> &str;
}