Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/catchers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,20 @@ pub fn not_found(req: &Request) -> Json<ErrorResponse> {
status: 404,
message: "Page not found".to_string(),
})
}

#[catch(500)]
pub fn internal_server_error(req: &Request) -> Json<ErrorResponse> {
Json(ErrorResponse {
status: 500,
message: "Internal Server Error".to_string(),
})
}

#[catch(204)]
pub fn no_content(req: &Request) -> Json<ErrorResponse> {
Json(ErrorResponse {
status: 204,
message: "No Content".to_string(),
})
}
5 changes: 3 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ mod catchers;
mod db;
mod schema;

use crate::routes::snack::{create_snack, list_snacks, update_snack};
use crate::routes::snack::{create_snack, delete_snack, list_snacks, update_snack};
use dotenv::dotenv;
use rocket::*;

Expand All @@ -28,6 +28,7 @@ fn index() -> &'static str {
fn rocket() -> _ {
dotenv().ok();

rocket::build().mount("/", routes![index, create_snack, list_snacks, update_snack]).register("/", catchers![catchers::unauthorized, catchers::not_found])
rocket::build().mount("/", routes![index, create_snack, list_snacks, update_snack, delete_snack]).register("/", catchers![catchers::unauthorized, catchers::not_found,
catchers::no_content, catchers::internal_server_error])
}

17 changes: 17 additions & 0 deletions src/routes/snack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,21 @@ pub fn update_snack(
}
})
}
#[delete("/snack/<snack_id>")]
pub fn delete_snack(_api_key: ApiKey, snack_id: i32) -> Status {
let mut conn = db::establish_connection();

match diesel::delete(snacks.find(snack_id)).execute(&mut conn) {
Ok(count) => {
if count > 0 {
Status::NoContent
} else {
Status::NotFound
}
}
Err(err) => {
println!("Database error: {:?}", err);
Status::InternalServerError
}
}
}