diff options
author | Santo Cariotti <santo@dcariotti.me> | 2021-03-17 09:57:56 +0100 |
---|---|---|
committer | Santo Cariotti <santo@dcariotti.me> | 2021-03-17 09:57:56 +0100 |
commit | 07b052797e273d4a85f2316e7ef9ca8677595dd1 (patch) | |
tree | ea1d6a222dbb59a19dedb83ca2b10edf19f9cab8 /src | |
parent | 0ed019b99d7603f19afbef8e676b342e3c868e76 (diff) |
feat: get commit by hash
Diffstat (limited to 'src')
-rw-r--r-- | src/commit/models.rs | 24 | ||||
-rw-r--r-- | src/commit/routes.rs | 20 |
2 files changed, 42 insertions, 2 deletions
diff --git a/src/commit/models.rs b/src/commit/models.rs index 6246511..c70ecf2 100644 --- a/src/commit/models.rs +++ b/src/commit/models.rs @@ -1,5 +1,5 @@ use crate::db::get_client; -use crate::errors::AppError; +use crate::errors::{AppError, AppErrorType}; use chrono::{DateTime, Local}; use deadpool_postgres::Pool; @@ -39,4 +39,26 @@ impl Commit { Ok(commits) } + + // Find a commit that it has an hash equals to `hash` + pub async fn find(pool: Pool, hash: String) -> Result<Commit, AppError> { + let client = get_client(pool.clone()).await.unwrap(); + let statement = client + .prepare("SELECT * FROM commit WHERE hash = $1") + .await?; + + let commit = client + .query_opt(&statement, &[&hash]) + .await? + .map(|row| Commit::from_row_ref(&row).unwrap()); + + match commit { + Some(commit) => Ok(commit), + None => Err(AppError { + error_type: AppErrorType::NotFoundError, + cause: None, + message: Some("Commit not found".to_string()), + }), + } + } } diff --git a/src/commit/routes.rs b/src/commit/routes.rs index bf04108..1b73c4f 100644 --- a/src/commit/routes.rs +++ b/src/commit/routes.rs @@ -19,10 +19,28 @@ async fn index(state: web::Data<AppState>) -> impl Responder { } } +// Endpoint used for getting one commit +async fn get_commit( + state: web::Data<AppState>, + hash: web::Path<(String,)>, +) -> impl Responder { + info!(state.log, "GET /commit/{}/", &hash.0); + + let result = Commit::find(state.pool.clone(), hash.0.clone()).await; + + result + .map(|commit| HttpResponse::Ok().json(commit)) + .map_err(|e| e) +} + /// Routes for commits pub fn config(cfg: &mut web::ServiceConfig) { cfg.service( web::scope("/commit") - .service(web::resource("{_:/?}").route(web::get().to(index))), + .service(web::resource("{_:/?}").route(web::get().to(index))) + .service( + web::resource("/{hash}{_:/?}") + .route(web::get().to(get_commit)), + ), ); } |