use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::string::ToString;
use crate::method::Method;
use product_os_http::Request;
use product_os_http_body::BodyBytes;
#[cfg(any(feature = "request", feature = "request_std"))]
pub struct ProductOSRequest<DReq: product_os_http_body::Body> {
pub url: String,
pub method: Method,
pub query: BTreeMap<String, String>,
pub headers: BTreeMap<String, String>,
pub body: Option<DReq>,
pub bearer_auth: Option<String>,
}
#[cfg(any(feature = "request", feature = "request_std"))]
impl<DReq: product_os_http_body::Body> ProductOSRequest<DReq> {
pub fn new(method: Method, url: &str) -> Self {
Self {
url: url.to_string(),
method,
query: BTreeMap::new(),
headers: BTreeMap::new(),
body: None,
bearer_auth: None,
}
}
pub fn add_header(&mut self, name: &str, value: &str, _is_sensitive: bool) {
self.headers.insert(name.to_string(), value.to_string());
}
pub fn add_headers(&mut self, headers: BTreeMap<String, String>, is_sensitive: bool) {
for (name, value) in headers {
self.add_header(name.as_str(), value.as_str(), is_sensitive);
}
}
pub fn add_param(&mut self, key: String, value: String) {
self.query.insert(key, value);
}
pub fn add_params(&mut self, params: BTreeMap<String, String>) {
for (k, v) in params {
self.query.insert(k, v);
}
}
pub fn set_query(&mut self, params: BTreeMap<String, String>) {
self.query = params;
}
pub fn set_body(&mut self, data: DReq) {
self.body = Some(data);
}
pub fn into_body(self) -> Option<DReq> {
self.body
}
pub fn bearer_auth(&mut self, token: String) {
self.bearer_auth = Some(token);
}
}
#[cfg(any(feature = "request", feature = "request_std"))]
impl ProductOSRequest<BodyBytes> {
pub fn from_request(r: Request<BodyBytes>) -> Self {
let (parts, body) = r.into_parts();
let url = parts.uri.to_string();
let method = crate::method::Method::from_http_method(&parts.method);
let mut query = BTreeMap::new();
if let Some(q) = parts.uri.query() {
for pair in q.split('&') {
if let Some((k, v)) = pair.split_once('=') {
query.insert(k.to_string(), v.to_string());
}
}
}
let mut headers = BTreeMap::new();
for (name, value) in parts.headers.iter() {
if let Ok(v) = value.to_str() {
headers.insert(name.to_string(), v.to_string());
}
}
let bearer_auth = parts
.headers
.get(product_os_http::header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.filter(|s| s.starts_with("Bearer "))
.map(|s| s.trim_start_matches("Bearer ").to_string());
let body = Some(body);
Self {
url,
method,
query,
headers,
body,
bearer_auth,
}
}
}