Skip to main content

picdl_rs/boosty/
mod.rs

1pub mod types;
2
3use log::debug;
4use types::Response;
5use crate::http::{client::{Headers, Query}, reqwest::ReqwestError};
6
7use super::http::{client::HttpClient, reqwest::ReqwestClient};
8
9/// Boosty client struct
10///
11/// # Example
12///
13/// Using an async http client (reqwest)
14/// ```no_test
15/// let client = picdl_rs::boosty::Boosty::<picdl_rs::http::reqwest::ReqwestClient>::new();
16/// ```
17#[derive(Debug, Clone, Copy)]
18pub struct Boosty<Http: HttpClient> {
19    http: Http,
20}
21
22/// Enum of possible errors
23#[derive(Debug)]
24pub enum BoostyError {
25    HttpError(ReqwestError),
26    SerdeError(serde_json::Error)
27}
28
29/// Implements conversion of ReqwestError to BoostyError
30impl From<ReqwestError> for BoostyError {
31    fn from(value: ReqwestError) -> Self {
32        Self::HttpError(value)
33    }
34}
35
36/// Implements conversion of serde_json::Error to BoostyError
37impl From<serde_json::Error> for BoostyError {
38    fn from(value: serde_json::Error) -> Self {
39        Self::SerdeError(value)
40    }
41}
42
43/// Boosty API client
44impl<Http: HttpClient> Boosty<Http>
45    where BoostyError: From<<Http as HttpClient>::Error> {
46    /// Returns a Gelbooru client with ReqwestClient as HTTP client
47    pub fn new() -> Boosty<ReqwestClient> {
48        Boosty{ http: <ReqwestClient as Default>::default() }
49    }
50
51    /// Fetches a specific count (`limit` argument) posts from blog (`blog` argument)
52    pub async fn fetch(&self, blog: &str, limit: i64) -> Result<Response, BoostyError> {
53        let headers = Headers::new();
54        let payload = Query::new();
55        debug!("Requesting {}", format!("https://api.boosty.to/v1/blog/{blog}/post/?limit={limit}"));
56        let response = self.http.get(
57            format!("https://api.boosty.to/v1/blog/{blog}/post/?limit={limit}"),
58            &headers,
59            &payload).await?;
60
61        let json: Response = serde_json::from_str(&response)?;
62        Ok(json) 
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use log::debug;
69    use crate::boosty::Boosty;
70    use crate::http::reqwest::ReqwestClient;
71
72    #[tokio::test]
73    async fn test_gelbooru_fetch() {
74        let _ = pretty_env_logger::try_init();
75        let client = Boosty::<ReqwestClient>::new();
76        let result = client.fetch("boosty", 1);
77        debug!("Post title: {:?}", result.await.unwrap().data[0].title);
78    }
79}