use apimock_routing::{ParsedRequest, Respond};
use console::style;
use std::path::Path;
use crate::{
http_util::delay_response,
respond_util::full_file_path,
response::{
error_response::internal_server_error_response,
file_response::FileResponse,
status_code_response::{status_code_response, status_code_response_with_message},
text_response::text_response,
},
types::BoxBody,
};
pub async fn respond_response(
respond: &Respond,
dir_prefix: &str,
parsed_request: &ParsedRequest,
rule_set_default_delay_ms: Option<u32>,
) -> Result<hyper::Response<BoxBody>, hyper::http::Error> {
if let Some(delay_ms) = respond
.delay_response_milliseconds
.or(rule_set_default_delay_ms)
{
delay_response(delay_ms).await;
}
let request_headers = &parsed_request.component_parts.headers;
if let Some(file_path) = respond.file_path.as_ref() {
let Some(full_file_path) = full_file_path(file_path.as_str(), dir_prefix) else {
log::error!(
"{}:\n{} (prefix = {})",
style("file not found").red(),
file_path,
dir_prefix,
);
return internal_server_error_response("failed to get response file", request_headers);
};
let _ = Path::new(dir_prefix);
return FileResponse::new_with_csv_records_jsonpath(
full_file_path.as_str(),
respond.headers.as_ref(),
respond.csv_records_key.clone(),
request_headers,
)
.file_content_response()
.await;
}
if let Some(text) = respond.text.as_ref() {
return match respond.status_code.as_ref() {
Some(status_code) => status_code_response_with_message(
status_code,
text.as_str(),
respond.headers.as_ref(),
request_headers,
),
None => text_response(
text.as_str(),
None,
respond.headers.as_ref(),
request_headers,
),
};
}
if let Some(status_code) = respond.status_code.as_ref() {
return status_code_response(status_code, respond.headers.as_ref(), request_headers);
}
internal_server_error_response("invalid respond def", request_headers)
}