Skip to content

Commit

Permalink
add the handler to delete a site for a specific category
Browse files Browse the repository at this point in the history
  • Loading branch information
huangcheng committed Nov 27, 2023
1 parent af9e583 commit 0de1633
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/bin/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ async fn main() -> Result<(), rocket::Error> {
category::add_site,
category::get_sites,
category::update_site,
category::delete_site,
],
)
.launch()
Expand Down
31 changes: 31 additions & 0 deletions src/handlers/category.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,3 +229,34 @@ pub async fn modify_site(

Ok(())
}

pub async fn delete_site(
category_id: &str,
site_id: &str,
state: &State<AppState>,
) -> 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(&state.pool)
.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(&state.pool)
.await?;

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

Ok(())
}
18 changes: 18 additions & 0 deletions src/routes/category.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,24 @@ pub async fn update_site<'r>(
Ok(())
}

#[delete("/<id>/site/<site_id>")]
pub async fn delete_site(
id: &str,
site_id: &str,
state: &State<AppState>,
_jwt: JwtMiddleware,
) -> Result<(), Status> {
category::delete_site(id, site_id, state)
.await
.map_err(|e| {
error!("{}", e);

e.into()
})?;

Ok(())
}

#[get("/<id>/sites")]
pub async fn get_sites(id: &str, state: &State<AppState>) -> Result<Json<Vec<Site>>, Status> {
let sites = category::get_sites(id, state).await.map_err(|e| {
Expand Down

0 comments on commit 0de1633

Please sign in to comment.