use uuid::Uuid;
use elastic_reqwest::{SyncBody, SyncElasticClient};
use reqwest::{Client as SyncHttpClient, ClientBuilder as SyncHttpClientBuilder};
use error::{self, Result};
use client::requests::HttpRequest;
use client::responses::{sync_response, SyncResponseBuilder};
use client::{private, Client, RequestParams, Sender};
pub type SyncClient = Client<SyncSender>;
#[derive(Clone)]
pub struct SyncSender {
pub(in client) http: SyncHttpClient,
}
impl private::Sealed for SyncSender {}
impl Sender for SyncSender {
type Body = SyncBody;
type Response = Result<SyncResponseBuilder>;
fn send<TRequest, TBody>(&self, req: TRequest, params: &RequestParams) -> Self::Response
where
TRequest: Into<HttpRequest<'static, TBody>>,
TBody: Into<Self::Body>,
{
let correlation_id = Uuid::new_v4();
let req = req.into();
info!(
"Elasticsearch Request: correlation_id: '{}', path: '{}'",
correlation_id,
req.url.as_ref()
);
let res = match self.http.elastic_req(params, req).map_err(error::request) {
Ok(res) => {
info!(
"Elasticsearch Response: correlation_id: '{}', status: '{}'",
correlation_id,
res.status()
);
res
}
Err(e) => {
error!(
"Elasticsearch Response: correlation_id: '{}', error: '{}'",
correlation_id,
e
);
Err(e)?
}
};
Ok(sync_response(res))
}
}
pub struct SyncClientBuilder {
http: Option<SyncHttpClient>,
params: RequestParams,
}
impl Default for SyncClientBuilder {
fn default() -> Self {
SyncClientBuilder::new()
}
}
impl SyncClientBuilder {
pub fn new() -> Self {
SyncClientBuilder {
http: None,
params: RequestParams::default(),
}
}
pub fn from_params(params: RequestParams) -> Self {
SyncClientBuilder {
http: None,
params: params,
}
}
pub fn base_url<I>(mut self, base_url: I) -> Self
where
I: Into<String>,
{
self.params = self.params.base_url(base_url);
self
}
pub fn params<F>(mut self, builder: F) -> Self
where
F: Fn(RequestParams) -> RequestParams,
{
self.params = builder(self.params);
self
}
pub fn http_client(mut self, client: SyncHttpClient) -> Self {
self.http = Some(client);
self
}
pub fn build(self) -> Result<SyncClient> {
let http = self.http
.map(Ok)
.unwrap_or_else(|| SyncHttpClientBuilder::new().build())
.map_err(error::build)?;
Ok(SyncClient {
sender: SyncSender { http: http },
params: self.params,
})
}
}