From 07b052797e273d4a85f2316e7ef9ca8677595dd1 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Wed, 17 Mar 2021 09:57:56 +0100 Subject: feat: get commit by hash --- src/commit/models.rs | 24 +++++++++++++++++++++++- src/commit/routes.rs | 20 +++++++++++++++++++- 2 files changed, 42 insertions(+), 2 deletions(-) (limited to 'src') 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 { + 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) -> impl Responder { } } +// Endpoint used for getting one commit +async fn get_commit( + state: web::Data, + 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)), + ), ); } -- cgit v1.2.3-18-g5258