diff options
-rw-r--r-- | src/db.rs | 1 | ||||
-rw-r--r-- | src/errors.rs | 2 | ||||
-rw-r--r-- | src/repository/models.rs | 5 | ||||
-rw-r--r-- | src/repository/routes.rs | 7 |
4 files changed, 15 insertions, 0 deletions
@@ -1,6 +1,7 @@ use crate::errors::AppError; use deadpool_postgres::{Client, Pool, PoolError}; +/// Return a valid `Client` to make SQL queries pub async fn get_client(pool: Pool) -> Result<Client, AppError> { pool.get() .await diff --git a/src/errors.rs b/src/errors.rs index 082315e..07df840 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -72,6 +72,8 @@ impl ResponseError for AppError { AppErrorType::NotFoundError => StatusCode::NOT_FOUND, } } + + /// Returns a JSON response with "detail" as key fn error_response(&self) -> HttpResponse { HttpResponse::build(self.status_code()).json(AppErrorResponse { detail: self.message(), diff --git a/src/repository/models.rs b/src/repository/models.rs index 54a93d7..c480cbe 100644 --- a/src/repository/models.rs +++ b/src/repository/models.rs @@ -9,6 +9,7 @@ use uuid::Uuid; #[derive(Serialize, Deserialize, PostgresMapper)] #[pg_mapper(table = "repository")] +/// Repository model pub struct Repository { pub id: Uuid, pub url: String, @@ -18,6 +19,9 @@ pub struct Repository { } impl Repository { + /// Find all repositories inside the database. + /// Make a select query and order the repositories by descrescent updated + /// datetime pub async fn find_all(pool: Pool) -> Result<Vec<Repository>, AppError> { let client = get_client(pool.clone()).await.unwrap(); let statement = client @@ -34,6 +38,7 @@ impl Repository { Ok(repos) } + /// Find a repository with an `id` equals to an Uuid element pub async fn find(pool: Pool, id: &Uuid) -> Result<Repository, AppError> { let client = get_client(pool.clone()).await.unwrap(); let statement = client diff --git a/src/repository/routes.rs b/src/repository/routes.rs index 634d210..0683b47 100644 --- a/src/repository/routes.rs +++ b/src/repository/routes.rs @@ -5,9 +5,12 @@ use actix_web::{web, HttpResponse, Responder}; use slog::info; use uuid::Uuid; +/// Endpoint used for retrieve all repositories async fn index(state: web::Data<AppState>) -> impl Responder { let result = Repository::find_all(state.pool.clone()).await; info!(state.log, "GET /repo/"); + + // If raises an `Err`, returns an error in JSON format match result { Ok(repos) => HttpResponse::Ok().json(repos), _ => HttpResponse::BadRequest().json(AppErrorResponse { @@ -17,12 +20,16 @@ async fn index(state: web::Data<AppState>) -> impl Responder { } } +/// Endpoint used for retrieve a repository that matches with an `id`. +/// It is a String, casted in an Uuid format. async fn get_repo( state: web::Data<AppState>, id: web::Path<(Uuid,)>, ) -> impl Responder { let result = Repository::find(state.pool.clone(), &id.0).await; info!(state.log, "GET /repo/{}/", id.0); + + // `map_err` is also used when repo is not found result .map(|repo| HttpResponse::Ok().json(repo)) .map_err(|e| e) |