Skip to content

Commit 6d4d640

Browse files
authored
Merge pull request #11 from QuantGeekDev/feature/delete-snack
Feature/delete snack
2 parents a7aeb90 + 4374356 commit 6d4d640

File tree

3 files changed

+36
-2
lines changed

3 files changed

+36
-2
lines changed

src/catchers/mod.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,20 @@ pub fn not_found(req: &Request) -> Json<ErrorResponse> {
2323
status: 404,
2424
message: "Page not found".to_string(),
2525
})
26+
}
27+
28+
#[catch(500)]
29+
pub fn internal_server_error(req: &Request) -> Json<ErrorResponse> {
30+
Json(ErrorResponse {
31+
status: 500,
32+
message: "Internal Server Error".to_string(),
33+
})
34+
}
35+
36+
#[catch(204)]
37+
pub fn no_content(req: &Request) -> Json<ErrorResponse> {
38+
Json(ErrorResponse {
39+
status: 204,
40+
message: "No Content".to_string(),
41+
})
2642
}

src/main.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ mod catchers;
88
mod db;
99
mod schema;
1010

11-
use crate::routes::snack::{create_snack, list_snacks, update_snack};
11+
use crate::routes::snack::{create_snack, delete_snack, list_snacks, update_snack};
1212
use dotenv::dotenv;
1313
use rocket::*;
1414

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

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

src/routes/snack.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,4 +67,21 @@ pub fn update_snack(
6767
}
6868
})
6969
}
70+
#[delete("/snack/<snack_id>")]
71+
pub fn delete_snack(_api_key: ApiKey, snack_id: i32) -> Status {
72+
let mut conn = db::establish_connection();
7073

74+
match diesel::delete(snacks.find(snack_id)).execute(&mut conn) {
75+
Ok(count) => {
76+
if count > 0 {
77+
Status::NoContent
78+
} else {
79+
Status::NotFound
80+
}
81+
}
82+
Err(err) => {
83+
println!("Database error: {:?}", err);
84+
Status::InternalServerError
85+
}
86+
}
87+
}

0 commit comments

Comments
 (0)