Skip to content

Commit

Permalink
modify handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
huangcheng committed Nov 29, 2023
1 parent 95b3ff6 commit c226794
Show file tree
Hide file tree
Showing 8 changed files with 170 additions and 57 deletions.
58 changes: 49 additions & 9 deletions src/handlers/category.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::Db;
pub async fn get_categories(
page: i64,
size: i64,
upload_url: &str,
db: &mut Connection<Db>,
) -> Result<WithTotal<response::category::Category>, ServiceError> {
let total = query(r#"SELECT COUNT(id) AS count FROM category"#)
Expand All @@ -19,7 +20,7 @@ pub async fn get_categories(
.get::<i64, &str>("count");

let categories = sqlx::query_as::<_, Category>(
r#"SELECT id, name, description, icon, created_at, updated_at FROM category LIMIT ? OFFSET ?"#,
r#"SELECT id, name, description, created_at, updated_at FROM category LIMIT ? OFFSET ?"#,
)
.bind(size)
.bind(page * size)
Expand All @@ -29,8 +30,23 @@ pub async fn get_categories(
Ok(WithTotal {
total,
data: categories
.into_iter()
.map(|category| category.into())
.iter()
.map(|category| {
let icon = category.icon.clone();

let icon = if icon.starts_with("http") || icon.starts_with("https") {
icon
} else {
format!("{}/{}", upload_url, icon)
};

response::category::Category {
id: category.id,
name: category.name.clone(),
description: category.description.clone(),
icon,
}
})
.collect(),
})
}
Expand All @@ -39,7 +55,7 @@ pub async fn update_category<'r>(
id: &'r str,
category: &'r UpdateCategory<'r>,
db: &mut Connection<Db>,
) -> Result<Category, ServiceError> {
) -> Result<(), ServiceError> {
let record = query_as::<_, Category>(
r#"SELECT id, name, description, icon, created_at, updated_at FROM category WHERE id = ?"#,
)
Expand All @@ -61,24 +77,28 @@ pub async fn update_category<'r>(
None => record.description,
};

let icon = match category.icon {
Some(icon) => String::from(icon),
None => record.icon,
};

let record = Category {
id: record.id,
name,
description,
icon: record.icon,
icon,
created_at: record.created_at,
updated_at: record.updated_at,
};

query(r#"UPDATE category SET name = ?, description = ?, icon = ? WHERE id = ?"#)
query(r#"UPDATE category SET name = ?, description = ? WHERE id = ?"#)
.bind(&record.name)
.bind(&record.description)
.bind(&record.icon)
.bind(record.id)
.execute(&mut ***db)
.await?;

Ok(record)
Ok(())
}

pub async fn add_category(
Expand Down Expand Up @@ -116,6 +136,7 @@ pub async fn delete_category(id: &str, db: &mut Connection<Db>) -> Result<(), Se

pub async fn get_sites(
category_id: &str,
upload_url: &str,
db: &mut Connection<Db>,
) -> Result<Vec<response::site::Site>, ServiceError> {
let sites = query_as::<_, response::site::Site>(
Expand All @@ -125,5 +146,24 @@ pub async fn get_sites(
.fetch_all(&mut ***db)
.await?;

Ok(sites)
Ok(sites
.iter()
.map(|site| {
let icon = site.icon.clone();

let icon = if icon.starts_with("http") || icon.starts_with("https") {
icon
} else {
format!("{}/{}", upload_url, icon)
};

response::site::Site {
id: site.id,
name: site.name.clone(),
url: site.url.clone(),
description: site.description.clone(),
icon,
}
})
.collect())
}
23 changes: 22 additions & 1 deletion src/handlers/site.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use crate::Db;
pub async fn get_sites(
page: i64,
size: i64,
upload_url: &str,
db: &mut Connection<Db>,
) -> Result<WithTotal<SiteWithCategory>, ServiceError> {
let count = query(r#"SELECT COUNT(id) AS count FROM site"#)
Expand All @@ -28,7 +29,27 @@ pub async fn get_sites(

Ok(WithTotal {
total: count,
data: sites,
data: sites
.iter()
.map(|site| {
let icon = site.icon.clone();

let icon = if icon.starts_with("http") || icon.starts_with("https") {
icon
} else {
format!("{}/{}", upload_url, icon)
};

SiteWithCategory {
id: site.id,
name: site.name.clone(),
url: site.url.clone(),
icon,
description: site.description.clone(),
category: site.category.clone(),
}
})
.collect(),
})
}

Expand Down
23 changes: 11 additions & 12 deletions src/handlers/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,16 @@ pub async fn get_user(
let user = query_as::<_, models::user::User>("SELECT * FROM user WHERE username = ?")
.bind(username)
.fetch_one(&mut ***db)
.await?;

let avatar = match user.avatar {
Some(avatar) => {
if avatar.starts_with("http") || avatar.starts_with("https") {
Some(avatar)
} else {
Some(format!("{}/{}", upload_url, avatar))
}
}
None => None,
.await
.map_err(|e| match e {
sqlx::Error::RowNotFound => ServiceError::Unauthorized,
_ => ServiceError::InternalServerError,
})?;

let avatar = if user.avatar.starts_with("http") || user.avatar.starts_with("https") {
user.avatar
} else {
format!("{}/{}", upload_url, user.avatar)
};

Ok(response::user::User {
Expand Down Expand Up @@ -64,7 +63,7 @@ pub async fn update_user(
};

let avatar = match user.avatar {
Some(avatar) => Some(String::from(avatar)),
Some(avatar) => String::from(avatar),
None => record.avatar,
};

Expand Down
2 changes: 1 addition & 1 deletion src/models/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ pub struct User {
pub nickname: String,
pub password: String,
pub email: String,
pub avatar: Option<String>,
pub avatar: String,
}
2 changes: 1 addition & 1 deletion src/response/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ pub struct User {
pub username: String,
pub nickname: String,
pub email: String,
pub avatar: Option<String>,
pub avatar: String,
}
67 changes: 48 additions & 19 deletions src/routes/category.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use std::ops::Deref;

use log::error;
use rocket::http::Status;
use rocket::serde::json::Json;
use rocket::{delete, get, post, put};
use rocket::{delete, get, post, put, State};
use rocket_db_pools::Connection;

use crate::config::Config;
use crate::handlers::category::{
self, add_category, delete_category, get_categories, update_category,
};
Expand All @@ -14,23 +13,27 @@ use crate::request::category::{CreateCategory, UpdateCategory};
use crate::response::category::Category;
use crate::response::site::Site;
use crate::response::WithTotal;
use crate::utils::standardize_url;
use crate::Db;

#[get("/?<page>&<size>")]
pub async fn all(
page: Option<i64>,
size: Option<i64>,
config: &State<Config>,
mut db: Connection<Db>,
) -> Result<Json<WithTotal<Category>>, Status> {
let page = page.unwrap_or(0);

let size = size.unwrap_or(10);

let result = get_categories(page, size, &mut db).await.map_err(|e| {
error!("{}", e);
let result = get_categories(page, size, &config.upload_url, &mut db)
.await
.map_err(|e| {
error!("{}", e);

e.into()
})?;
e.into()
})?;

Ok(Json(result))
}
Expand All @@ -39,27 +42,47 @@ pub async fn all(
pub async fn update<'r>(
id: &'r str,
category: Json<UpdateCategory<'r>>,
config: &State<Config>,
mut db: Connection<Db>,
_jwt: JwtMiddleware,
) -> Result<(), Status> {
update_category(id, category.deref(), &mut db)
.await
.map_err(|e| {
error!("{}", e);
let mut category = category.into_inner();

e.into()
})?;
let icon = match category.icon {
Some(icon) => standardize_url(icon, &config.upload_url),
None => None,
};

category.icon = icon.as_deref();

update_category(id, &category, &mut db).await.map_err(|e| {
error!("{}", e);

e.into()
})?;

Ok(())
}

#[post("/", format = "json", data = "<category>")]
pub async fn add<'r>(
category: Json<CreateCategory<'r>>,
config: &State<Config>,
mut db: Connection<Db>,
_jwt: JwtMiddleware,
) -> Result<(), Status> {
add_category(category.deref(), &mut db).await.map_err(|e| {
let mut category = category.into_inner();

let icon = standardize_url(category.icon, &config.upload_url);

let icon = match icon {
Some(icon) => String::from(icon),
None => String::from(category.icon),
};

category.icon = icon.as_str();

add_category(&category, &mut db).await.map_err(|e| {
error!("{}", e);

e.into()
Expand All @@ -84,12 +107,18 @@ pub async fn delete<'r>(
}

#[get("/<id>/sites")]
pub async fn get_sites(id: &str, mut db: Connection<Db>) -> Result<Json<Vec<Site>>, Status> {
let sites = category::get_sites(id, &mut db).await.map_err(|e| {
error!("{}", e);
pub async fn get_sites(
id: &str,
config: &State<Config>,
mut db: Connection<Db>,
) -> Result<Json<Vec<Site>>, Status> {
let sites = category::get_sites(id, &config.upload_url, &mut db)
.await
.map_err(|e| {
error!("{}", e);

e.into()
})?;
e.into()
})?;

Ok(Json(sites))
}
Loading

0 comments on commit c226794

Please sign in to comment.