use crate::{
error::{
EasyAlgoliaError,
ErrorKind,
},
Client,
};
use std::mem;
use secrecy::{
ExposeSecret,
Secret,
};
pub struct ClientBuilder {
application_id: Option<Secret<String>>,
api_key: Option<Secret<String>>,
}
impl ClientBuilder {
pub fn new() -> Self {
Self {
application_id: None,
api_key: None,
}
}
pub fn set_application_id(mut self, app_id: &str) -> Self {
self.application_id = Some(Secret::new(String::from(app_id)));
self
}
pub fn set_api_key(mut self, app_id: &str) -> Self {
self.api_key = Some(Secret::new(String::from(app_id)));
self
}
pub fn build<'a>(&mut self) -> Result<Client, EasyAlgoliaError> {
if self.api_key.is_some() && self.application_id.is_some() {
let api_key = mem::take(&mut self.api_key);
let application_id = mem::take(&mut self.application_id);
return Ok(Client::new(
api_key.unwrap().expose_secret(),
application_id.unwrap().expose_secret(),
));
} else {
Err(EasyAlgoliaError::new(
ErrorKind::ClientBuilderError,
Some(" unable to fetch client id or api key ".into()),
))
}
}
pub fn build_from_env<'a>() -> Result<Client, EasyAlgoliaError> {
use std::env;
let app_id = env::var("ALGOLIA_APPLICATION_ID").map_err(|_| {
EasyAlgoliaError::new(ErrorKind::ClientBuilderError, Some("failed to fetch desireed Envviroment variables, ALGOLIA_APPLICATION_ID is not set. ".into()))
})?;
let api_key = env::var("ALGOLIA_API_KEY").map_err(|_| {
EasyAlgoliaError::new(
ErrorKind::ClientBuilderError,
Some("unable to load env ,ALGOLIA_API_KEY is not set".into()),
)
})?;
let client = Client::new(&api_key, &app_id);
Ok(client)
}
}