get.rs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. use actix_web::{get, web, HttpResponse};
  2. use serde::Serialize;
  3. use serde_json::json;
  4. use sqlx::PgPool;
  5. use uuid::Uuid;
  6. use crate::auth::AuthUser;
  7. use crate::models::exercise::{Exercise, ExerciseType};
  8. use crate::models::workout::Workout;
  9. #[derive(Serialize)]
  10. struct ExerciseResponse {
  11. id: Uuid,
  12. name: String,
  13. notes: Option<String>,
  14. exercise_type: ExerciseType,
  15. }
  16. impl From<Exercise> for ExerciseResponse {
  17. fn from(e: Exercise) -> Self {
  18. Self {
  19. id: e.id,
  20. name: e.name,
  21. notes: e.notes,
  22. exercise_type: e.exercise_type,
  23. }
  24. }
  25. }
  26. #[get("/workout/{id}")]
  27. pub async fn get_workout(
  28. pool: web::Data<PgPool>,
  29. _auth: AuthUser,
  30. path: web::Path<Uuid>,
  31. ) -> HttpResponse {
  32. let id = path.into_inner();
  33. let workout = match Workout::find_by_id(pool.get_ref(), id).await {
  34. Ok(Some(w)) => w,
  35. Ok(None) => return HttpResponse::NotFound().json(json!({"error": "Workout not found"})),
  36. Err(_) => {
  37. return HttpResponse::InternalServerError().json(json!({"error": "An error occurred"}))
  38. }
  39. };
  40. let exercises = match Exercise::find_by_workout(pool.get_ref(), id).await {
  41. Ok(e) => e,
  42. Err(_) => {
  43. return HttpResponse::InternalServerError().json(json!({"error": "An error occurred"}))
  44. }
  45. };
  46. let exercises: Vec<ExerciseResponse> = exercises.into_iter().map(Into::into).collect();
  47. HttpResponse::Ok().json(json!({
  48. "id": workout.id,
  49. "name": workout.name,
  50. "exercises": exercises,
  51. }))
  52. }