summaryrefslogtreecommitdiff
path: root/src/routes/problem.rs
blob: 69d1b668cf732e5f860f6d04100992639f5961ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
use axum::{extract::{Path, State}, http::StatusCode, response::{IntoResponse, Json}};
use serde::Deserialize;

use crate::{AppState, routes::errors::RouteError};

#[derive(Deserialize)]
pub struct CreateProblemRequest {
    title: String,
    description: String,
}

pub async fn create_problem(
    State(state): State<AppState>,
    Json(request): Json<CreateProblemRequest>
) -> Result<impl IntoResponse, RouteError> {

    let Ok(problem) = state.database.insert_problem(&request.title, &request.description) else {
        return Err(RouteError::Internal("database action failed".into()));
    };

    Ok((StatusCode::CREATED, Json(problem)))
}

pub async fn get_problems(
    State(state): State<AppState>,
) -> Result<impl IntoResponse, RouteError> {

    let Ok(problems) = state.database.fetch_problems() else {
        return Err(RouteError::Internal("database action failed".into()));
    };

    Ok((StatusCode::CREATED, Json(problems)))
}

pub async fn get_problem(
    State(state): State<AppState>,
    Path(problem_id): Path<i64>,
) -> Result<impl IntoResponse, RouteError> {
    match state.database.fetch_problem(problem_id) {
        Err(_) => Err(RouteError::Internal("database action failed".into())),
        Ok(None) => Err(RouteError::NotFound("problem".into())),
        Ok(Some(problem)) => Ok(Json(problem))
    }
}