First attempt at refactoring out a CouchDB client.

This commit is contained in:
Dorian 2018-07-28 13:36:46 -04:00
parent 3e70d7f0ae
commit 79111c5c11
1 changed files with 58 additions and 10 deletions

View File

@ -50,8 +50,8 @@ struct CouchDBQuery<T> {
}
#[derive(Serialize, Deserialize)]
struct CouchDBUserResult {
docs: Vec<User>,
struct CouchDBUserResult<T> {
docs: Vec<T>,
}
#[derive(Serialize)]
@ -76,18 +76,66 @@ fn status(_req: HttpRequest) -> impl Responder {
})
}
pub static ENV_COUCHDB_URI: &'static str = "ROOKERIES_COUCHDB";
#[allow(dead_code)]
pub struct CouchDbServer {
pub base_uri: String,
username: String,
password: String,
database: String,
}
impl CouchDbServer {
pub fn configure_from_env() -> Result<CouchDbServer, env::VarError> {
let couchdb_uri = env::var(ENV_COUCHDB_URI)?;
// TODO: Configure from string properly.
Ok(CouchDbServer{
base_uri: couchdb_uri,
username: String::from("admin"),
password: String::from("password"),
database: String::from("rookeries"),
})
}
// pub fn find<M, T>(&self, query: CouchDBQuery<M>) -> Result<Vec<T>, Error> {
//
// let client = Client::new();
// let couchdb_uri = format!("{}/_find/", &self.base_uri);
//
// let post_request = client.post(&couchdb_uri)
// .basic_auth(&self.username, Some(&self.password))
// .json(&query)
// .send();
//
// if post_request.is_err() {
// Err(post_request.unwrap_err())
// }
//
// let mut response = post_request.unwrap();
// if response.status() != StatusCode::Ok {
// error!("request error: {}", &response.status());
// Err(&response)
// };
//
// let results: CouchDBUserResult<T> = response.json().unwrap();
// Ok(results.docs)
// }
}
fn auth(credentials: Json<UserCredentialsRequest>) -> impl Responder {
let db_connection = match env::var("ROOKERIES_COUCHDB") {
Ok(db_uri) => db_uri,
Err(err) => {
error!("Missing '{}' because: {:}", ENV_JWT_SECRET_KEY, err);
return json_error_message(
let couchdb = CouchDbServer::configure_from_env();
if couchdb.is_err() {
error!("Missing '{}'", ENV_COUCHDB_URI);
return json_error_message(
StatusCode::InternalServerError,
"Server not configured correctly",
);
}
};
}
// TODO: Migrate find command into a standalone function.
let db_connection = couchdb.unwrap().base_uri;
// TODO: Consider wrapping everything into a CouchDB client of sorts.
// TODO: Clean up this entire thing.
@ -117,7 +165,7 @@ fn auth(credentials: Json<UserCredentialsRequest>) -> impl Responder {
return json_error_message(StatusCode::Unauthorized, "Invalid credentials provided.");
};
let results: CouchDBUserResult = response.json().unwrap();
let results: CouchDBUserResult<User> = response.json().unwrap();
if results.docs.len() == 0 {
info!("User '{}' could not be found.", &credentials.username);
return json_error_message(StatusCode::Unauthorized, "Invalid credentials provided.");