Skip to main content

grp_core/
request.rs

1use reqwest::{Client, IntoUrl, RequestBuilder, Response};
2use serde::Serialize;
3
4use super::config::Config;
5use super::error::types::ErrorType;
6use super::platform::Platform;
7use super::error::structs::Error;
8
9impl Platform {
10    async fn send(req: RequestBuilder) -> Result<Response, Error> {
11        req.send().await.map_err( |e| Error::new(
12            ErrorType::FetchFailed, 
13            vec![e.to_string(), "Please check your ethernet conection".to_string()]
14        ))
15    }
16    pub async fn get<U: IntoUrl>(&self, url: U, auth: bool, config: &Config) -> Result<Response, Error> {
17        let client = Client::new();
18        let mut header = self.get_auth_header(&config.token);
19        
20        if !auth {
21            match self {
22                Platform::Github => header.remove("Authorization"),
23                Platform::Gitea |
24                Platform::Codeberg |
25                Platform::Forgejo |
26                Platform::Gitlab => header.remove("authorization"),
27            };
28        }
29        
30        let req = client.get(url).headers(header);
31        
32        Platform::send(req).await
33    }
34    pub async fn post<T, U>(&self, url: U, header: bool, config: &Config, json: &T) -> Result<Response, Error>
35    where
36        U: IntoUrl,
37        T: Serialize + ?Sized,
38    {
39        let client = Client::new();
40        
41        let mut request = client
42            .post(url)
43            .header("content-type", "application/json")
44            .json(json);
45        
46        if header {
47            request = request.headers(self.get_auth_header(&config.token));
48        }
49        
50        Platform::send(request).await
51    }
52    
53    pub async fn delete<U: IntoUrl>(&self, url: U, config: &Config) -> Result<Response, Error> {
54        let client = Client::new();
55        
56        let req = client
57            .delete(url)
58            .headers(self.get_auth_header(&config.token));
59        
60        Platform::send(req).await
61    }
62}