|
| 1 | +use axum::{ |
| 2 | + extract::{Path, State}, |
| 3 | + http::StatusCode, |
| 4 | + response::Json, |
| 5 | + routing::get, |
| 6 | + Router, |
| 7 | +}; |
| 8 | +use std::sync::Arc; |
| 9 | + |
| 10 | +use crate::api::AppState; |
| 11 | +use crate::application::ApplicationError; |
| 12 | + |
| 13 | +fn map_error(e: ApplicationError) -> (StatusCode, Json<serde_json::Value>) { |
| 14 | + let (status, message) = if e.not_found() { |
| 15 | + (StatusCode::NOT_FOUND, e.to_string()) |
| 16 | + } else { |
| 17 | + (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()) |
| 18 | + }; |
| 19 | + (status, Json(serde_json::json!({ "error": message }))) |
| 20 | +} |
| 21 | + |
| 22 | +pub async fn get_course( |
| 23 | + State(state): State<Arc<AppState>>, |
| 24 | +) -> Result<Json<crate::domain::Course>, (StatusCode, Json<serde_json::Value>)> { |
| 25 | + state.get_course.execute().map(Json).map_err(map_error) |
| 26 | +} |
| 27 | + |
| 28 | +pub async fn get_lesson( |
| 29 | + State(state): State<Arc<AppState>>, |
| 30 | + Path(lesson_id): Path<String>, |
| 31 | +) -> Result<Json<crate::domain::Lesson>, (StatusCode, Json<serde_json::Value>)> { |
| 32 | + state |
| 33 | + .get_lesson |
| 34 | + .execute(&lesson_id) |
| 35 | + .map(Json) |
| 36 | + .map_err(map_error) |
| 37 | +} |
| 38 | + |
| 39 | +pub async fn get_all_lessons( |
| 40 | + State(state): State<Arc<AppState>>, |
| 41 | +) -> Result<Json<Vec<crate::domain::Lesson>>, (StatusCode, Json<serde_json::Value>)> { |
| 42 | + state |
| 43 | + .get_all_lessons |
| 44 | + .execute() |
| 45 | + .map(Json) |
| 46 | + .map_err(map_error) |
| 47 | +} |
| 48 | + |
| 49 | +pub async fn get_chapter( |
| 50 | + State(state): State<Arc<AppState>>, |
| 51 | + Path(chapter_id): Path<String>, |
| 52 | +) -> Result<Json<crate::domain::Chapter>, (StatusCode, Json<serde_json::Value>)> { |
| 53 | + state |
| 54 | + .get_chapter |
| 55 | + .execute(&chapter_id) |
| 56 | + .map(Json) |
| 57 | + .map_err(map_error) |
| 58 | +} |
| 59 | + |
| 60 | +pub fn router(state: Arc<AppState>) -> Router { |
| 61 | + Router::new() |
| 62 | + .route("/api/course", get(get_course)) |
| 63 | + .route("/api/lessons", get(get_all_lessons)) |
| 64 | + .route("/api/lessons/:lesson_id", get(get_lesson)) |
| 65 | + .route("/api/chapters/:chapter_id", get(get_chapter)) |
| 66 | + .with_state(state) |
| 67 | +} |
0 commit comments