use crate::error::BaseError;
use crate::http::response::Response;
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use reqwest::{Client, Method};
use serde::Serialize;
use std::time::Duration;
pub struct RequestBuilder {
client: Client,
method: Method,
url: String,
headers: HeaderMap,
query_params: Vec<(String, String)>,
body: Option<Vec<u8>>,
timeout: Duration,
token: Option<String>,
}
impl RequestBuilder {
pub(crate) fn new(
client: Client,
method: Method,
url: String,
timeout: Duration,
token: Option<String>,
) -> Self {
Self {
client,
method,
url,
headers: HeaderMap::new(),
query_params: Vec::new(),
body: None,
timeout,
token,
}
}
pub fn header(mut self, name: &str, value: &str) -> Self {
if let (Ok(name), Ok(value)) = (
HeaderName::from_bytes(name.as_bytes()),
HeaderValue::from_str(value),
) {
self.headers.insert(name, value);
}
self
}
pub fn headers(mut self, headers: Vec<(&str, &str)>) -> Self {
for (name, value) in headers {
if let (Ok(name), Ok(value)) = (
HeaderName::from_bytes(name.as_bytes()),
HeaderValue::from_str(value),
) {
self.headers.insert(name, value);
}
}
self
}
pub fn content_type(self, content_type: &str) -> Self {
self.header("Content-Type", content_type)
}
pub fn bearer_token(mut self, token: &str) -> Self {
self.token = Some(token.to_string());
self
}
pub fn user_agent(self, user_agent: &str) -> Self {
self.header("User-Agent", user_agent)
}
pub fn query(mut self, key: &str, value: &str) -> Self {
self.query_params.push((key.to_string(), value.to_string()));
self
}
pub fn queries(mut self, params: Vec<(&str, &str)>) -> Self {
for (key, value) in params {
self.query_params.push((key.to_string(), value.to_string()));
}
self
}
pub fn json<T: Serialize>(mut self, json: &T) -> Result<Self, BaseError> {
let json_str =
serde_json::to_vec(json).map_err(|e| BaseError::JsonSerializeFailed(e.to_string()))?;
self.body = Some(json_str);
self = self.content_type("application/json");
Ok(self)
}
pub fn form(mut self, form: Vec<(&str, &str)>) -> Self {
let form_str = form
.iter()
.map(|(k, v)| format!("{}={}", k, v))
.collect::<Vec<_>>()
.join("&");
self.body = Some(form_str.into_bytes());
self = self.content_type("application/x-www-form-urlencoded");
self
}
pub fn body(mut self, body: Vec<u8>) -> Self {
self.body = Some(body);
self
}
pub fn text(mut self, text: &str) -> Self {
self.body = Some(text.as_bytes().to_vec());
self = self.content_type("text/plain");
self
}
pub fn timeout(mut self, timeout_secs: u64) -> Self {
self.timeout = Duration::from_secs(timeout_secs);
self
}
pub async fn send(self) -> Result<Response, BaseError> {
let mut request = self
.client
.request(self.method, &self.url)
.timeout(self.timeout);
request = request.headers(self.headers);
if let Some(token) = self.token {
request = request.bearer_auth(token);
}
if !self.query_params.is_empty() {
request = request.query(&self.query_params);
}
if let Some(body) = self.body {
request = request.body(body);
}
let response = request
.send()
.await
.map_err(|e| BaseError::HttpRequestFailed(e.to_string()))?;
Ok(Response::new(response))
}
}