gitignore_template_generator/http_client/
impls.rs1use std::{collections::HashMap, time::Duration};
2
3use ureq::Agent;
4
5use crate::{
6 constant,
7 core::{ExitKind, ProgramExit},
8 http_client::api::HttpClient,
9};
10
11#[derive(Default)]
13pub struct UreqHttpClient {
14 pub server_url: String,
18
19 pub global_timeout: Option<Duration>,
21}
22
23pub struct MockHttpClient {
25 pub response: Result<String, ProgramExit>,
28}
29
30pub struct MockEndpointHttpClient {
32 pub response: HashMap<String, Result<String, ProgramExit>>,
35}
36
37impl HttpClient for UreqHttpClient {
38 fn get(&self, url: &str) -> Result<String, ProgramExit> {
45 let full_url = format!("{}{url}", self.server_url);
46 let agent: Agent = Agent::config_builder()
47 .timeout_global(Some(
48 self.global_timeout.unwrap_or(Duration::from_secs(
49 constant::template_manager::TIMEOUT
50 .parse()
51 .expect(constant::error_messages::FAILED_U64_CONVERSION),
52 )),
53 ))
54 .build()
55 .into();
56
57 let result = agent.get(full_url).call();
58
59 match result {
60 Ok(mut response) => match response.body_mut().read_to_string() {
61 Ok(body) => Ok(body.trim().to_string()),
62 Err(error) => Err(ProgramExit {
63 message: error.to_string(),
64 exit_status: constant::exit_status::HTTP_CLIENT_ERROR,
65 styled_message: None,
66 kind: ExitKind::Error,
67 }),
68 },
69 Err(error) => Err(ProgramExit {
70 message: constant::error_messages::API_CALL_FAILURE
71 .replace("{error}", &error.to_string()),
72 exit_status: constant::exit_status::GENERIC,
73 styled_message: None,
74 kind: ExitKind::Error,
75 }),
76 }
77 }
78}
79
80impl HttpClient for MockHttpClient {
81 fn get(&self, _url: &str) -> Result<String, ProgramExit> {
86 self.response.clone()
87 }
88}
89
90impl HttpClient for MockEndpointHttpClient {
91 fn get(&self, url: &str) -> Result<String, ProgramExit> {
96 self.response[url].clone()
97 }
98}