use std::{fs, io::Error, path::Path};
use crate::{const_vars, DataResult, DataResultFormat};
use mime::Mime;
use polars::export::chrono::Local;
use polars::frame::DataFrame;
use reqwest::{header, Request, Response};
pub struct HttpClient;
impl HttpClient {
pub(crate) async fn _exec(
request: Request,
call_back_body: fn(body: String) -> DataResult<DataFrame>,
) -> Result<DataResult<DataFrame>, anyhow::Error> {
tracing::debug!("request url: {:?}", request);
let http_client = reqwest::Client::new();
let response = http_client.execute(request).await?;
let body = response.text().await?;
Ok(call_back_body(body))
}
pub async fn exec_by_format(
request: Request,
format: impl DataResultFormat,
) -> Result<DataResult<DataFrame>, anyhow::Error> {
tracing::debug!("request url: {:?}", request);
let http_client = reqwest::Client::new();
let response = http_client.execute(request).await?;
match response.text().await {
Ok(body) => {
if let Ok(data_frame) = format.to_dataframe(Some(body)) {
return Ok(format.format(data_frame.data));
}
}
Err(e) => {
tracing::warn!("http response text error:{}", e);
}
}
Ok(DataResult::default())
}
fn _get_content_type(resp: &Response) -> Option<Mime> {
resp.headers()
.get(header::CONTENT_TYPE)
.map(|v| v.to_str().unwrap().parse().unwrap())
}
fn _process_body_to_dataframe(
m: Option<Mime>,
body: &String,
) -> Result<DataResult<DataFrame>, anyhow::Error> {
match m {
None => Ok(DataResult::<DataFrame>::from(body.to_string())),
Some(v) if v == mime::APPLICATION_JSON => {
Ok(DataResult::<DataFrame>::from(body.to_string()))
}
_ => Ok(DataResult::<DataFrame>::from(body.to_string())),
}
}
}
pub struct Envs;
impl Envs {
pub fn cache_temp_home() -> String {
dotenvy::var(const_vars::CACHE_TEMP_HOME).unwrap()
}
}
pub struct DateUtils;
impl DateUtils {
pub fn now_fmt_ymd() -> String {
let now = Local::now();
now.format("%Y-%m-%d").to_string()
}
}
pub struct IoUtils;
impl IoUtils {
pub fn create_dir_recursive(path: &Path) -> Result<(), Error> {
if path.exists() {
Ok(())
} else {
match path.parent() {
Some(parent) => IoUtils::create_dir_recursive(parent),
None => fs::create_dir(path),
}
}
}
}