Skip to content

Commit

Permalink
adjust handlers for site
Browse files Browse the repository at this point in the history
  • Loading branch information
huangcheng committed Nov 28, 2023
1 parent 1fbe1b5 commit fadf5d5
Show file tree
Hide file tree
Showing 6 changed files with 182 additions and 208 deletions.
4 changes: 1 addition & 3 deletions src/bin/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,11 @@ async fn main() -> Result<(), rocket::Error> {
category::update,
category::add,
category::delete,
category::add_site,
category::get_sites,
category::update_site,
category::delete_site,
],
)
.mount("/api/sites", routes![site::all])
.mount("/api/site", routes![site::add, site::update, site::delete])
.mount("/api/upload", routes![upload])
.launch()
.await?;
Expand Down
146 changes: 0 additions & 146 deletions src/handlers/category.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,40 +114,6 @@ pub async fn delete_category(id: &str, db: &mut Connection<Db>) -> Result<(), Se
Ok(())
}

pub async fn add_site(
category_id: &str,
site: &CreateSite<'_>,
db: &mut Connection<Db>,
) -> Result<(), ServiceError> {
query_as::<_, Category>(
r#"SELECT id, name, description, created_at, updated_at FROM category WHERE id = ?"#,
)
.bind(category_id)
.fetch_one(&mut ***db)
.await
.map_err(|e| match e {
sqlx::Error::RowNotFound => ServiceError::BadRequest(String::from("Category not found")),
_ => ServiceError::DatabaseError(e),
})?;

let id = query(r#"INSERT INTO site (name, url, description, icon) VALUES (?, ?, ?, ?)"#)
.bind(site.name)
.bind(site.url)
.bind(site.description)
.bind(site.icon)
.execute(&mut ***db)
.await?
.last_insert_id();

query(r#"INSERT INTO category_site (category_id, site_id) VALUES (?, ?)"#)
.bind(category_id)
.bind(id)
.execute(&mut ***db)
.await?;

Ok(())
}

pub async fn get_sites(
category_id: &str,
db: &mut Connection<Db>,
Expand All @@ -161,115 +127,3 @@ pub async fn get_sites(

Ok(sites)
}

pub async fn modify_site(
category_id: &str,
site_id: &str,
site: &UpdateSite<'_>,
db: &mut Connection<Db>,
) -> Result<(), ServiceError> {
let record = query_as::<_, Site>(
r#"SELECT id, name, url, description, icon, created_at, updated_at FROM site WHERE id = ?"#,
)
.bind(site_id)
.fetch_one(&mut ***db)
.await
.map_err(|e| match e {
sqlx::Error::RowNotFound => ServiceError::BadRequest(String::from("Site not found")),
_ => ServiceError::DatabaseError(e),
})?;

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

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

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

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

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

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

let category_id = match site.category_id {
Some(category_id) => format!("{}", category_id),
None => category_id.to_string(),
};

query(r#"SELECT id FROM category WHERE id = ?"#)
.bind(&category_id)
.fetch_one(&mut ***db)
.await
.map_err(|e| match e {
sqlx::Error::RowNotFound => {
ServiceError::BadRequest(String::from("Category not found"))
}
_ => ServiceError::DatabaseError(e),
})?;

query(r#"UPDATE category_site SET category_id = ? WHERE site_id = ?"#)
.bind(&category_id)
.bind(record.id)
.execute(&mut ***db)
.await?;

Ok(())
}

pub async fn delete_site(
category_id: &str,
site_id: &str,
db: &mut Connection<Db>,
) -> Result<(), ServiceError> {
query(
r#"SELECT category_id, site_id FROM category_site WHERE category_id = ? AND site_id = ?"#,
)
.bind(category_id)
.bind(site_id)
.fetch_one(&mut ***db)
.await
.map_err(|e| match e {
sqlx::Error::RowNotFound => ServiceError::BadRequest(String::from("Site not found")),
_ => ServiceError::DatabaseError(e),
})?;

query(r#"DELETE FROM category_site WHERE category_id = ? AND site_id = ?"#)
.bind(category_id)
.bind(site_id)
.execute(&mut ***db)
.await?;

query(r#"DELETE FROM site WHERE id = ?"#)
.bind(site_id)
.execute(&mut ***db)
.await?;

Ok(())
}
129 changes: 128 additions & 1 deletion src/handlers/site.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ use rocket_db_pools::Connection;
use sqlx::{query, query_as, Row};

use crate::errors::ServiceError;
use crate::models::category::Category;
use crate::models::site::Site;
use crate::request::site::{CreateSite, UpdateSite};
use crate::response::site::SiteWithCategory;
use crate::response::WithTotal;
use crate::Db;
Expand All @@ -17,11 +20,135 @@ pub async fn get_sites(
.get::<i64, &str>("count");

let sites = query_as::<_, SiteWithCategory>(
r#"SELECT site.id AS id, site.name AS name, site.url AS url, site.icon AS icon, site.description AS description, category.name AS category FROM site INNER JOIN category INNER JOIN category_site ON site.id = category_site.site_id AND category.id = category_site.category_id LIMIT ? OFFSET ?"#,
r#"SELECT site.id AS id, site.name AS name, site.url AS url, site.icon AS icon, site.description AS description, category.name AS category FROM site
INNER JOIN category
INNER JOIN category_site ON site.id = category_site.site_id AND category.id = category_site.category_id LIMIT ? OFFSET ?
"#,
).bind(size).bind(page * size).fetch_all(&mut ***db).await?;

Ok(WithTotal {
total: count,
data: sites,
})
}

pub async fn add_site(site: &CreateSite<'_>, db: &mut Connection<Db>) -> Result<(), ServiceError> {
query_as::<_, Category>(
r#"SELECT id, name, description, created_at, updated_at FROM category WHERE id = ?"#,
)
.bind(site.category)
.fetch_one(&mut ***db)
.await
.map_err(|e| match e {
sqlx::Error::RowNotFound => ServiceError::BadRequest(String::from("Category not found")),
_ => ServiceError::DatabaseError(e),
})?;

let id = query(r#"INSERT INTO site (name, url, description, icon) VALUES (?, ?, ?, ?)"#)
.bind(site.name)
.bind(site.url)
.bind(site.description)
.bind(site.icon)
.execute(&mut ***db)
.await?
.last_insert_id();

query(r#"INSERT INTO category_site (category_id, site_id) VALUES (?, ?)"#)
.bind(site.category)
.bind(id)
.execute(&mut ***db)
.await?;

Ok(())
}

pub async fn update_site(
site_id: &str,
site: &UpdateSite<'_>,
db: &mut Connection<Db>,
) -> Result<(), ServiceError> {
let record = query_as::<_, Site>(
r#"SELECT id, name, url, description, icon, created_at, updated_at FROM site WHERE id = ?"#,
)
.bind(site_id)
.fetch_one(&mut ***db)
.await
.map_err(|e| match e {
sqlx::Error::RowNotFound => ServiceError::BadRequest(String::from("Site not found")),
_ => ServiceError::DatabaseError(e),
})?;

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

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

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

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

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

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

if let Some(category) = site.category {
query(r#"SELECT id FROM category WHERE id = ?"#)
.bind(category)
.fetch_one(&mut ***db)
.await
.map_err(|e| match e {
sqlx::Error::RowNotFound => {
ServiceError::BadRequest(String::from("Category not found"))
}
_ => ServiceError::DatabaseError(e),
})?;

query(r#"UPDATE category_site SET category_id = ? WHERE site_id = ?"#)
.bind(category)
.bind(record.id)
.execute(&mut ***db)
.await?;
}

Ok(())
}

pub async fn delete_site(id: &str, db: &mut Connection<Db>) -> Result<(), ServiceError> {
query(r#"DELETE FROM category_site WHERE site_id = ?"#)
.bind(id)
.execute(&mut ***db)
.await?;

query(r#"DELETE FROM site WHERE id = ?"#)
.bind(id)
.execute(&mut ***db)
.await?;

Ok(())
}
3 changes: 2 additions & 1 deletion src/request/site.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub struct CreateSite<'r> {
pub url: &'r str,
pub description: &'r str,
pub icon: &'r str,
pub category: i64,
}

#[derive(Debug, Deserialize)]
Expand All @@ -13,5 +14,5 @@ pub struct UpdateSite<'r> {
pub url: Option<&'r str>,
pub description: Option<&'r str>,
pub icon: Option<&'r str>,
pub category_id: Option<i64>,
pub category: Option<i64>,
}
Loading

0 comments on commit fadf5d5

Please sign in to comment.