From 72f5010988a758be2710287657000b5adae1ead4 Mon Sep 17 00:00:00 2001 From: Nikita Vilunov Date: Fri, 26 Apr 2024 12:28:13 +0200 Subject: [PATCH] clean up http.rs a little --- src/http.rs | 45 ++++++++++++++++++++------------------------- 1 file changed, 20 insertions(+), 25 deletions(-) diff --git a/src/http.rs b/src/http.rs index 4bf3ffe..b39a6f2 100644 --- a/src/http.rs +++ b/src/http.rs @@ -111,14 +111,7 @@ async fn endpoint_create_player( ) -> Result>> { let str = request.collect().await?.to_bytes(); let Ok(res) = serde_json::from_slice::(&str[..]) else { - let payload = ErrorResponse { - code: errors::MALFORMED_REQUEST, - message: "The request payload contains incorrect JSON value", - } - .to_body(); - let mut response = Response::new(payload); - *response.status_mut() = StatusCode::BAD_REQUEST; - return Ok(response); + return Ok(malformed_request()); }; storage.create_user(&res.name).await?; log::info!("Player {} created", res.name); @@ -129,18 +122,11 @@ async fn endpoint_create_player( async fn endpoint_set_password( request: Request, - mut storage: Storage, + storage: Storage, ) -> Result>> { let str = request.collect().await?.to_bytes(); let Ok(res) = serde_json::from_slice::(&str[..]) else { - let payload = ErrorResponse { - code: errors::MALFORMED_REQUEST, - message: "The request payload contains incorrect JSON value", - } - .to_body(); - let mut response = Response::new(payload); - *response.status_mut() = StatusCode::BAD_REQUEST; - return Ok(response); + return Ok(malformed_request()); }; let verdict = Authenticator::new(&storage).set_password(&res.player_name, &res.password).await?; match verdict { @@ -173,19 +159,28 @@ pub fn not_found() -> Response> { response } +fn malformed_request() -> Response> { + let payload = ErrorResponse { + code: errors::MALFORMED_REQUEST, + message: "The request payload contains incorrect JSON value", + } + .to_body(); + + let mut response = Response::new(payload); + *response.status_mut() = StatusCode::BAD_REQUEST; + return response; +} + trait Or5xx { fn or5xx(self) -> Response>; } impl Or5xx for Result>> { fn or5xx(self) -> Response> { - match self { - Ok(e) => e, - Err(e) => { - let mut response = Response::new(Full::new(e.to_string().into())); - *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; - response - } - } + self.unwrap_or_else(|e| { + let mut response = Response::new(Full::new(e.to_string().into())); + *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; + response + }) } }