-
Notifications
You must be signed in to change notification settings - Fork 77
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Sergio Castaño Arteaga <[email protected]>
- Loading branch information
Showing
7 changed files
with
537 additions
and
508 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
use axum::{ | ||
extract, | ||
extract::Extension, | ||
http::{ | ||
header::{HeaderMap, HeaderName, HeaderValue}, | ||
StatusCode, | ||
}, | ||
response, | ||
}; | ||
use deadpool_postgres::Pool; | ||
use serde::{Deserialize, Serialize}; | ||
use serde_json::Value; | ||
use tokio_postgres::types::Json; | ||
use uuid::Uuid; | ||
|
||
/// Header that indicates the number of items available for pagination purposes. | ||
const PAGINATION_TOTAL_COUNT: &str = "pagination-total-count"; | ||
|
||
/// Query input used when searching for projects. | ||
#[derive(Debug, Serialize, Deserialize)] | ||
pub(crate) struct SearchProjectsInput { | ||
limit: Option<usize>, | ||
offset: Option<usize>, | ||
text: Option<String>, | ||
category: Option<Vec<usize>>, | ||
maturity: Option<Vec<usize>>, | ||
rating: Option<Vec<char>>, | ||
} | ||
|
||
/// Handler that allows searching for projects. | ||
pub(crate) async fn search_projects( | ||
Extension(db_pool): Extension<Pool>, | ||
extract::Json(input): extract::Json<SearchProjectsInput>, | ||
) -> Result<(HeaderMap, response::Json<Value>), (StatusCode, String)> { | ||
// Search projects in database | ||
let db = db_pool.get().await.map_err(internal_error)?; | ||
let row = db | ||
.query_one("select * from search_projects($1::jsonb)", &[&Json(input)]) | ||
.await | ||
.map_err(internal_error)?; | ||
let Json(projects): Json<Value> = row.get("projects"); | ||
let total_count: i64 = row.get("total_count"); | ||
|
||
// Prepare response headers | ||
let mut headers = HeaderMap::new(); | ||
headers.insert( | ||
HeaderName::from_static(PAGINATION_TOTAL_COUNT), | ||
HeaderValue::from_str(&total_count.to_string()).unwrap(), | ||
); | ||
|
||
Ok((headers, response::Json(projects))) | ||
} | ||
|
||
/// Handler that returns the requested project. | ||
pub(crate) async fn get_project( | ||
Extension(db_pool): Extension<Pool>, | ||
extract::Path(project_id): extract::Path<Uuid>, | ||
) -> Result<response::Json<Value>, (StatusCode, String)> { | ||
// Get project from database | ||
let db = db_pool.get().await.map_err(internal_error)?; | ||
let row = db | ||
.query_one("select get_project($1::uuid)", &[&project_id]) | ||
.await | ||
.map_err(internal_error)?; | ||
let Json(project): Json<Value> = row.get(0); | ||
|
||
Ok(response::Json(project)) | ||
} | ||
|
||
/// Helper for mapping any error into a `500 Internal Server Error` response. | ||
fn internal_error<E>(err: E) -> (StatusCode, String) | ||
where | ||
E: std::error::Error, | ||
{ | ||
(StatusCode::INTERNAL_SERVER_ERROR, err.to_string()) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
use crate::handlers::*; | ||
use anyhow::Error; | ||
use axum::{ | ||
http::StatusCode, | ||
routing::{get, get_service, post}, | ||
AddExtensionLayer, Router, | ||
}; | ||
use config::Config; | ||
use deadpool_postgres::Pool; | ||
use std::path::Path; | ||
use tower::ServiceBuilder; | ||
use tower_http::{ | ||
services::{ServeDir, ServeFile}, | ||
trace::TraceLayer, | ||
}; | ||
|
||
/// Setup API server router. | ||
pub(crate) fn setup(cfg: &Config, db_pool: Pool) -> Result<Router, Error> { | ||
// Setup some paths | ||
let static_path = cfg.get_str("apiserver.staticPath")?; | ||
let index_path = Path::new(&static_path).join("index.html"); | ||
|
||
// Setup error handler | ||
let error_handler = |err: std::io::Error| async move { | ||
( | ||
StatusCode::INTERNAL_SERVER_ERROR, | ||
format!("internal error: {}", err), | ||
) | ||
}; | ||
|
||
// Setup router | ||
let router = Router::new() | ||
.route("/api/projects/search", post(search_projects)) | ||
.route("/api/projects/:project_id", get(get_project)) | ||
.route( | ||
"/", | ||
get_service(ServeFile::new(index_path)).handle_error(error_handler), | ||
) | ||
.nest( | ||
"/static", | ||
get_service(ServeDir::new(static_path)).handle_error(error_handler), | ||
) | ||
.layer( | ||
ServiceBuilder::new() | ||
.layer(TraceLayer::new_for_http()) | ||
.layer(AddExtensionLayer::new(db_pool)), | ||
); | ||
|
||
Ok(router) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.