Created
October 5, 2024 07:21
-
-
Save krzkrzkrz/ce9b341887773e205463919dc49ef4ad to your computer and use it in GitHub Desktop.
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
use crate::database::tasks::{self, Entity as Task}; | |
use axum::{ | |
extract::{Path, Query}, | |
http::StatusCode, | |
Extension, Json, | |
}; | |
use sea_orm::{ColumnTrait, Condition, DatabaseConnection, EntityTrait, QueryFilter}; | |
use serde::{Deserialize, Serialize}; | |
#[derive(Serialize)] | |
pub struct ResponseTask { | |
id: i32, | |
title: String, | |
priority: Option<String>, | |
description: Option<String>, | |
} | |
pub async fn get_one_task( | |
Path(task_id): Path<i32>, | |
Extension(database): Extension<DatabaseConnection>, | |
) -> Result<Json<ResponseTask>, StatusCode> { | |
let task = Task::find_by_id(task_id).one(&database).await.unwrap(); | |
if let Some(task) = task { | |
Ok(Json(ResponseTask { | |
id: task.id, | |
title: task.title, | |
priority: task.priority, | |
description: task.description, | |
})) | |
} else { | |
Err(StatusCode::NOT_FOUND) | |
} | |
} | |
#[derive(Deserialize)] | |
pub struct GetTasksQueryParams { | |
title: Option<String>, | |
priority: Option<String>, | |
} | |
//curl -i "http://localhost:3000/tasks" | |
//curl -i "http://localhost:3000/tasks?priority=A" | |
//curl -i "http://localhost:3000/tasks?priorty=A&title=I%20a" | |
pub async fn get_all_tasks( | |
Extension(database): Extension<DatabaseConnection>, | |
Query(query_params): Query<GetTasksQueryParams>, | |
) -> Result<Json<Vec<ResponseTask>>, StatusCode> { | |
let priority_filter = Condition::all().add_option(query_params.priority.map(|priority| { | |
if priority.is_empty() { | |
tasks::Column::Priority.is_null() | |
} else { | |
tasks::Column::Priority.eq(priority) | |
} | |
})); | |
let title_filter = Condition::all().add_option(query_params.title.map(|title| { | |
if title.is_empty() { | |
tasks::Column::Title.is_null() | |
} else { | |
tasks::Column::Title.contains(title) | |
} | |
})); | |
let tasks = Task::find() | |
.filter(priority_filter) | |
.filter(title_filter) | |
.all(&database) | |
.await | |
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? | |
.into_iter() | |
.map(|task| ResponseTask { | |
id: task.id, | |
title: task.title, | |
priority: task.priority, | |
description: task.description, | |
}) | |
.collect(); | |
Ok(Json(tasks)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment