Split request and conversion for easier debugging

This commit is contained in:
Leon Grünewald 2024-01-01 21:50:57 +01:00
parent ec2b8f7b0d
commit 0c882667dc
2 changed files with 34 additions and 19 deletions

View file

@ -8,7 +8,7 @@ edition = "2021"
[dependencies] [dependencies]
anyhow = "1.0.77" anyhow = "1.0.77"
base64 = "0.21.5" base64 = "0.21.5"
reqwest = { version = "0.11.23", features = ["json"] } reqwest = "0.11.23"
serde = { version = "1.0.193", features = ["derive", "std"] } serde = { version = "1.0.193", features = ["derive", "std"] }
serde_json = "1.0.108" serde_json = "1.0.108"
thiserror = "1.0.52" thiserror = "1.0.52"

View file

@ -1,8 +1,10 @@
use std::io::Write;
use anyhow::Result; use anyhow::Result;
use base64::Engine; use base64::Engine;
use base64::engine::{GeneralPurpose}; use base64::engine::{GeneralPurpose};
use crate::post::{Post, Posts}; use crate::post::{Post, Posts};
use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderValue, USER_AGENT}; use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderValue, USER_AGENT};
use reqwest::Response;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Client<'a> { pub struct Client<'a> {
@ -38,31 +40,44 @@ impl<'a> Client<'a> {
base64_engine.encode(format!("{username}:{apikey}")) base64_engine.encode(format!("{username}:{apikey}"))
} }
pub async fn list_posts(&mut self, limit: Option<u16>, tags: Option<Vec<String>>, page: Option<u32>) -> Result<Vec<Post>> { async fn list_posts_raw(&mut self, limit: Option<u16>, tags: Option<Vec<String>>, page: Option<u32>) -> Result<Response> {
let mut url = url::Url::parse(format!("{}/posts.json", self.host).as_str())?; let mut url = url::Url::parse(format!("{}/posts.json", self.host).as_str())?;
let mut query_params = Vec::new(); let mut query_params = Vec::new();
if let Some(limit) = limit { if let Some(limit) = limit {
query_params.push(format!("limit={limit}")); query_params.push(format!("limit={limit}"));
} }
if let Some(page) = page { if let Some(page) = page {
query_params.push(format!("page={page}")); query_params.push(format!("page={page}"));
} }
if let Some(tags) = tags { if let Some(tags) = tags {
if tags.len() > 0 { if tags.len() > 0 {
query_params.push(format!("tags={}", tags.join(","))); query_params.push(format!("tags={}", tags.join(",")));
} }
} }
url.set_query(Some(&query_params.join("&"))); url.set_query(Some(&query_params.join("&")));
Ok(self.http_client.get(url.as_str()) Ok(self.http_client.get(url.as_str())
.send() .send()
.await? .await?)
.json::<Posts>() }
.await?.into())
pub async fn list_posts(&mut self, limit: Option<u16>, tags: Option<Vec<String>>, page: Option<u32>) -> Result<Vec<Post>> {
let res = self.list_posts_raw(limit, tags, page).await?;
let text = res.text().await?;
/*
let mut debug_file = std::fs::OpenOptions::new()
.write(true)
.create(true)
.open("./debug.json")?;
debug_file.write_all(text.as_bytes())?;
*/
Ok(serde_json::from_str(text.as_str())?)
} }
} }