refactor into dedicated function

This commit is contained in:
Luna 2023-04-04 22:22:18 -03:00
parent d33ab7540c
commit c435f8038d
1 changed files with 38 additions and 21 deletions

View File

@ -1,3 +1,4 @@
use axum::body::Bytes;
use axum::extract::{Multipart, Query}; use axum::extract::{Multipart, Query};
use axum::http::StatusCode; use axum::http::StatusCode;
use axum::response::{IntoResponse, Response}; use axum::response::{IntoResponse, Response};
@ -66,6 +67,36 @@ async fn test_handler() -> Result<(), AppError> {
Ok(()) Ok(())
} }
async fn send_image_to_dd(
file_contents: Vec<u8>,
file_name: String,
file_mime_type: &str,
options: &Options,
) -> anyhow::Result<WrappedResponse> {
let part = reqwest::multipart::Part::bytes(file_contents)
.file_name(file_name)
.mime_str(file_mime_type)
.unwrap();
let form = reqwest::multipart::Form::new().part("file", part);
log::debug!("calling dd");
let resp = reqwest::Client::new()
.post("http://localhost:4443")
.multipart(form)
.header("authorization", "Bearer 123")
.query(&[("threshold", options.threshold.clone())])
.send()
.await?;
let body = resp.text().await?;
log::info!("body: {}", &body);
let json_response: WrappedResponse = serde_json::from_str(&body)?;
log::debug!("called!");
Ok(json_response)
}
#[debug_handler] #[debug_handler]
async fn upload_file( async fn upload_file(
options: Query<Options>, options: Query<Options>,
@ -90,27 +121,13 @@ async fn upload_file(
} }
if let Some(file_contents) = maybe_file_contents { if let Some(file_contents) = maybe_file_contents {
let part = reqwest::multipart::Part::bytes(file_contents.to_vec()) let json_response = send_image_to_dd(
.file_name(maybe_file_name.unwrap()) file_contents.to_vec(),
.mime_str(maybe_file_type.unwrap().as_ref()) maybe_file_name.unwrap(),
.unwrap(); &maybe_file_type.unwrap(),
let form = reqwest::multipart::Form::new().part("file", part); &options,
)
log::debug!("calling dd"); .await?;
let resp = reqwest::Client::new()
.post("http://localhost:4443")
.multipart(form)
.header("authorization", "Bearer 123")
.query(&[("threshold", options.threshold.clone())])
.send()
.await?;
let body = resp.text().await?;
log::info!("body: {}", &body);
let json_response: WrappedResponse = serde_json::from_str(&body)?;
log::debug!("called!");
Ok((StatusCode::OK, Json(json_response))) Ok((StatusCode::OK, Json(json_response)))
} else { } else {
Ok(( Ok((