-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclients.rs
More file actions
60 lines (52 loc) · 1.73 KB
/
clients.rs
File metadata and controls
60 lines (52 loc) · 1.73 KB
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
use std::fmt;
use reqwest::Url;
use serde::de::DeserializeOwned;
use crate::model::metadata::Metadata;
pub trait Client {
fn metadata(&self) -> impl Future<Output = Result<Metadata, ClientError>> + Send;
}
pub type ClientResult<T> = Result<T, ClientError>;
pub struct TiledClient {
pub address: Url,
}
impl TiledClient {
async fn request<T: DeserializeOwned>(&self, endpoint: &str) -> ClientResult<T> {
println!("Requesting data from tiled");
let url = self.address.join(endpoint)?;
let response = reqwest::get(url).await?.error_for_status()?;
let body = response.text().await?;
serde_json::from_str(&body).map_err(|e| ClientError::InvalidResponse(e, body))
}
}
impl Client for TiledClient {
async fn metadata(&self) -> ClientResult<Metadata> {
self.request::<Metadata>("/api/v1/").await
}
}
#[derive(Debug)]
pub enum ClientError {
InvalidPath(url::ParseError),
ServerError(reqwest::Error),
InvalidResponse(serde_json::Error, String),
}
impl From<url::ParseError> for ClientError {
fn from(err: url::ParseError) -> ClientError {
ClientError::InvalidPath(err)
}
}
impl From<reqwest::Error> for ClientError {
fn from(err: reqwest::Error) -> ClientError {
ClientError::ServerError(err)
}
}
impl std::fmt::Display for ClientError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ClientError::InvalidPath(err) => write!(f, "Invalid URL path: {}", err),
ClientError::ServerError(err) => write!(f, "Tiled server error: {}", err),
ClientError::InvalidResponse(err, actual) => {
write!(f, "Invalid response: {err}, response: {actual}")
}
}
}
}