-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.rs
More file actions
69 lines (59 loc) · 2.03 KB
/
client.rs
File metadata and controls
69 lines (59 loc) · 2.03 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
61
62
63
64
65
66
67
68
69
use anyhow::{Context, Result};
use reqwest::{Client, StatusCode};
use std::time::Duration;
use crate::config::Config;
use crate::models::WebhookRequest;
pub struct WebhookClient {
client: Client,
base_url: String,
}
impl WebhookClient {
pub fn new(config: &Config) -> Self {
let client = Client::builder()
.timeout(Duration::from_secs(30))
.build()
.expect("Failed to create HTTP client");
Self {
client,
base_url: config.get_base_url().to_string(),
}
}
pub async fn get_requests(&self, token: &str, count: u32) -> Result<Vec<WebhookRequest>> {
let url = Config::join_url_segments(&self.base_url, &[token, "log", &count.to_string()]);
let response = self
.client
.get(&url)
.header(reqwest::header::ACCEPT, "application/json")
.send()
.await
.with_context(|| format!("Failed to fetch requests from {}", url))?;
let status = response.status();
if status.is_success() {
let response_text = response
.text()
.await
.with_context(|| "Failed to read response body")?;
let requests: Vec<WebhookRequest> =
serde_json::from_str(&response_text).with_context(|| {
format!(
"Failed to parse response as JSON. Response body: {}",
response_text
)
})?;
Ok(requests)
} else if status == StatusCode::NOT_FOUND {
Ok(vec![]) // No requests yet
} else {
let response_body = response
.text()
.await
.unwrap_or_else(|_| "(failed to read response body)".to_string());
anyhow::bail!(
"HTTP {} {}: {}",
status.as_u16(),
status.canonical_reason().unwrap_or("Unknown"),
response_body
);
}
}
}