From 97ffa100d67ac1ea7fdec1f4a720447a15476e70 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Tue, 23 Mar 2021 21:33:55 +0100 Subject: feat: search more than one commit --- src/commit/models.rs | 34 ++++++++++++++++++++++++++-------- src/commit/routes.rs | 20 +++++++++++++++++--- 2 files changed, 43 insertions(+), 11 deletions(-) diff --git a/src/commit/models.rs b/src/commit/models.rs index cec135a..2925955 100644 --- a/src/commit/models.rs +++ b/src/commit/models.rs @@ -32,20 +32,38 @@ pub struct CommitNumAuthor { impl Commit { /// Find all commits. Order them by descrescent `date` field - pub async fn find_all(pool: Pool) -> Result, AppError> { + /// `commit_hash` is used to search commit that matches with some sha codes + pub async fn find_all( + pool: Pool, + commit_hash: &String, + ) -> Result, AppError> { let client = get_client(pool.clone()).await.unwrap(); - let statement = client - .prepare("SELECT * FROM commit ORDER BY date DESC LIMIT 300") - .await?; - let commits = client - .query(&statement, &[]) - .await? + let query; + let hash; + if commit_hash != "" { + hash = format!("%{}%", commit_hash); + query = "SELECT * FROM commit WHERE hash LIKE $1 ORDER BY date DESC LIMIT 300"; + } else { + hash = String::new(); + query = "SELECT * FROM commit ORDER BY date DESC LIMIT 300" + } + + let statement = client.prepare(query).await?; + + let commits; + if hash != "" { + commits = client.query(&statement, &[&hash]).await?; + } else { + commits = client.query(&statement, &[]).await?; + } + + let result = commits .iter() .map(|row| Commit::from_row_ref(row).unwrap()) .collect::>(); - Ok(commits) + Ok(result) } // Find a commit that it has an hash equals to `hash` diff --git a/src/commit/routes.rs b/src/commit/routes.rs index 95a74a2..a1da519 100644 --- a/src/commit/routes.rs +++ b/src/commit/routes.rs @@ -4,12 +4,26 @@ use crate::errors::{AppError, AppErrorResponse, AppErrorType}; use actix_web::http::header; use actix_web::{web, HttpRequest, HttpResponse, Responder}; use slog::info; +use std::collections::HashMap; use std::env; /// Endpoint used for getting all commits -async fn index(state: web::Data) -> impl Responder { - info!(state.log, "GET /commit/"); - let result = Commit::find_all(state.pool.clone()).await; +async fn index( + req: HttpRequest, + state: web::Data, +) -> impl Responder { + let query = + web::Query::>::from_query(req.query_string()) + .unwrap(); + + let hash = match query.get("q") { + Some(x) => x.clone(), + None => String::new(), + }; + + info!(state.log, "GET /commit/?q={}", &hash); + + let result = Commit::find_all(state.pool.clone(), &hash).await; match result { Ok(commits) => HttpResponse::Ok().json(commits), -- cgit v1.2.3-18-g5258