1use reqwest::{
2 Client as ReqwestClient, ClientBuilder as ReqwestClientBuilder, Proxy, RequestBuilder,
3};
4
5#[derive(Debug)]
6pub struct ClientBuilder {
7 api_key: Option<String>,
8 api_url: String,
9 reqwest_client_builder: ReqwestClientBuilder,
10}
11
12impl ClientBuilder {
13 pub fn new() -> ClientBuilder {
15 ClientBuilder {
16 api_key: None,
17 api_url: "https://kodik-api.com".to_owned(),
18 reqwest_client_builder: ReqwestClientBuilder::new(),
19 }
20 }
21
22 pub fn api_key(mut self, api_key: impl Into<String>) -> ClientBuilder {
31 self.api_key = Some(api_key.into());
32 self
33 }
34
35 pub fn api_url(mut self, api_url: impl Into<String>) -> ClientBuilder {
46 self.api_url = api_url.into();
47 self
48 }
49
50 pub fn proxy(mut self, proxy: Proxy) -> ClientBuilder {
57 self.reqwest_client_builder = self.reqwest_client_builder.proxy(proxy);
58 self
59 }
60
61 pub fn custom_reqwest_builder(mut self, builder: ReqwestClientBuilder) -> ClientBuilder {
68 self.reqwest_client_builder = builder;
69 self
70 }
71
72 pub fn build(self) -> Client {
82 Client {
83 api_key: self.api_key.expect("api key is required"),
84 api_url: self.api_url,
85 http_client: self
86 .reqwest_client_builder
87 .build()
88 .expect("failed to build reqwest client"),
89 }
90 }
91}
92
93impl Default for ClientBuilder {
94 fn default() -> Self {
95 Self::new()
96 }
97}
98
99#[derive(Debug, Clone)]
101pub struct Client {
102 api_key: String,
103 api_url: String,
104 http_client: ReqwestClient,
105}
106
107impl Client {
108 pub fn new(api_key: impl Into<String>) -> Client {
120 ClientBuilder::new().api_key(api_key).build()
121 }
122
123 pub(crate) fn init_post_request(&self, path_or_url: &str) -> RequestBuilder {
124 if !path_or_url.starts_with("http") {
125 self.http_client
126 .post(self.api_url.clone() + path_or_url)
127 .query(&[("token", &self.api_key)])
128 } else {
129 self.http_client.post(path_or_url.to_owned())
130 }
131 }
132}