Skip to main content

mlb_api/request/
mod.rs

1use serde::de::DeserializeOwned;
2use crate::types::MLBError;
3
4#[cfg(feature = "ureq")]
5mod ureq;
6
7#[cfg(feature = "ureq")]
8pub use ureq::*;
9
10#[cfg(feature = "reqwest")]
11mod reqwest;
12#[cfg(feature = "reqwest")]
13pub use reqwest::*;
14
15pub type Result<T, E = Error> = std::result::Result<T, E>;
16
17#[derive(Debug, thiserror::Error)]
18pub enum Error {
19	#[cfg(feature = "ureq")]
20	#[error(transparent)]
21	Network(#[from] ::ureq::Error),
22	#[cfg(feature = "reqwest")]
23	#[error(transparent)]
24	Network(#[from] ::reqwest::Error),
25	#[cfg(not(all(test, debug_assertions)))]
26	#[error(transparent)]
27	Serde(#[from] serde_json::Error),
28	#[cfg(all(test, debug_assertions))]
29	#[error(transparent)]
30	Serde(#[from] serde_path_to_error::Error<serde_json::Error>),
31	#[error(transparent)]
32	MLB(#[from] MLBError),
33}
34
35#[cfg(all(feature = "reqwest", feature = "ureq"))]
36compile_error!("Only one http backend is allowed!");
37
38pub trait RequestURL: ToString {
39	type Response: DeserializeOwned;
40
41	#[cfg(feature = "ureq")]
42	fn get(&self) -> Result<Self::Response>
43	where
44		Self: Sized,
45	{
46		let url = self.to_string();
47		get::<Self::Response>(url)
48	}
49
50	#[cfg(feature = "reqwest")]
51	fn get(&self) -> impl Future<Output = Result<Self::Response>>
52	where
53		Self: Sized,
54	{
55		let url = self.to_string();
56		get::<Self::Response>(url)
57	}
58}
59
60pub trait RequestURLBuilderExt where Self: Sized {
61	type Built: RequestURL + From<Self>;
62
63	#[cfg(feature = "ureq")]
64	fn build_and_get(self) -> Result<<Self::Built as RequestURL>::Response> {
65		let built = Self::Built::from(self);
66		let url = built.to_string();
67		get::<<Self::Built as RequestURL>::Response>(url)
68	}
69
70	#[cfg(feature = "reqwest")]
71	fn build_and_get(self) -> impl Future<Output = Result<<Self::Built as RequestURL>::Response>> {
72		async {
73			let built = Self::Built::from(self);
74			let url = built.to_string();
75			get::<<Self::Built as RequestURL>::Response>(url).await
76		}
77	}
78}
79