#[allow(unused_imports)]
use crate::api::RequestFailure;
use crate::node;
use crate::objects::{ListOfObjects, response_to_list};
#[derive(Debug)]
pub struct SearchRequest<'a> {
api_key: &'a str,
file_error: String,
limit: u32,
offset: u32,
query: String,
server: &'a str,
space_id: Option<String>,
}
impl<'a> SearchRequest<'a> {
pub fn from_file(api_key: &'a str, server: &'a str, filename: &str) -> Self {
match std::fs::read_to_string(filename) {
Ok(s) => SearchRequest::from_str(api_key, server, s),
Err(e) => SearchRequest {
api_key,
file_error: format!("{e:?}"),
limit: 0,
offset: 0,
query: "".to_string(),
server,
space_id: None,
},
}
}
pub fn from_str(api_key: &'a str, server: &'a str, json_str: String) -> Self {
SearchRequest {
api_key,
offset: 0,
limit: 100,
file_error: "".to_string(),
query: json_str,
server,
space_id: None,
}
}
pub fn file_error(&self) -> &String {
&self.file_error
}
pub fn offset(mut self, offset: u32) -> Self {
self.offset = offset;
self
}
pub fn limit(mut self, limit: u32) -> Self {
self.limit = limit;
self
}
pub fn space_id(mut self, space_id: &str) -> Self {
self.space_id = Some(space_id.to_string());
self
}
pub async fn send(&self) -> Result<ListOfObjects, RequestFailure> {
let endpoint = match self.space_id.clone() {
Some(space_id) => format!("/v1/spaces/{}/search", space_id),
None => format!("/v1/search"),
};
match node::post(self.api_key, self.server, &endpoint, &self.query).await {
Ok(response) => {
if response.status() == http::StatusCode::OK {
return Ok(response_to_list(response).await);
} else {
let possible_status: Vec<http::StatusCode> = Vec::from([
http::StatusCode::BAD_REQUEST,
http::StatusCode::UNAUTHORIZED,
http::StatusCode::INTERNAL_SERVER_ERROR,
]);
return Err(RequestFailure::api_error(response, possible_status).await);
}
}
Err(e) => Err(RequestFailure::reqwest_error(e)),
}
}
}