use crate::client::couchdb::models::Security;
use crate::regexes::COUCHDB_DB_RULE;
use awc::Client;
pub mod errors;
use errors::DBSecureError;
pub async fn secure_db(
client: &Client,
db_name: &str,
data: Security,
host: &str,
) -> Result<bool, Box<dyn std::error::Error>> {
if !COUCHDB_DB_RULE.is_match(db_name) {
return Err(Box::new(DBSecureError::new(&format!(
"{} string doesn't respect the regex rule {}",
db_name,
COUCHDB_DB_RULE.as_str()
))));
}
let uri: String = format!("{}/{}/_security", host, db_name,);
match client.put(&uri).send_json(&data).await {
Ok(mut response) => {
if response.status().as_u16() >= 400 {
let bytes: Vec<u8> = response.body().await?.iter().cloned().collect();
let error: serde_json::Value =
serde_json::from_str(std::str::from_utf8(bytes.as_slice()).unwrap()).unwrap();
Err(Box::new(DBSecureError::new(&format!(
"Error with the request to {}: error: \n{}",
&uri, error
))))
} else {
Ok(true)
}
}
Err(error) => Err(Box::new(DBSecureError::new(&format!(
"Error with the request to {}: error: \n{}",
host, error
)))),
}
}
#[cfg(test)]
mod tests {}