use super::*;
#[derive(Debug)]
pub struct ClientBuilder<T: ClientAdapter> {
index: Option<String>,
host: Option<String>,
#[cfg(feature = "es_7")]
doc_type: Option<String>,
credentials: Option<Credentials>,
default_limit: Option<usize>,
adapter: Option<T>,
}
#[derive(Debug, thiserror::Error)]
pub enum BuilderError {
#[error("Adapter Setup Failed: {0}")]
AdapterSetup(#[from] adapter::AdapterError),
#[error("Missing or Bad Data Fields: {0}")]
BadData(String),
}
impl<T: ClientAdapter> Default for ClientBuilder<T> {
fn default() -> Self {
Self {
index: None,
host: None,
#[cfg(feature = "es_7")]
doc_type: None,
credentials: None,
default_limit: None,
adapter: None,
}
}
}
impl<T: ClientAdapter> ClientBuilder<T> {
pub fn host<S: Into<String>>(mut self, host: S) -> Self {
self.host = Some(host.into());
self
}
pub fn index<S: Into<String>>(mut self, index: S) -> Self {
self.index = Some(index.into());
self
}
#[cfg(feature = "es_7")]
pub fn doc_type<S: Into<String>>(mut self, doc_type: S) -> Self {
self.doc_type = Some(doc_type.into());
self
}
pub fn credentials<S, V>(mut self, username: S, password: V) -> Self
where
S: Into<String>,
V: Into<String>,
{
let credentials = Credentials {
username: username.into(),
password: password.into(),
};
self.credentials = Some(credentials);
self
}
pub fn default_limit(mut self, limit: usize) -> Self {
self.default_limit = Some(limit);
self
}
pub fn use_adapter(mut self, adapter: T) -> Self {
self.adapter = Some(adapter);
self
}
pub fn build(mut self) -> Result<Client<T>, BuilderError> {
let settings = self.build_settings()?;
let adapter = if let Some(adapter) = self.adapter {
adapter
} else {
T::try_new_from(&settings)?
};
Ok(Client { adapter, settings })
}
fn build_settings(&mut self) -> Result<Settings, BuilderError> {
let mut missing_fields = vec![];
if self.host.is_none() {
missing_fields.push("HOST");
}
if self.index.is_none() {
missing_fields.push("INDEX");
}
if !missing_fields.is_empty() {
return Err(BuilderError::BadData(missing_fields.join(",")));
}
Ok(Settings {
host: self.host.take().unwrap(),
index: self.index.take().unwrap(),
#[cfg(feature = "es_7")]
doc_type: self.doc_type.take(),
credentials: self.credentials.take(),
default_limit: self.default_limit.take(),
})
}
}