From d67cedc8476639c43c17d61e380047b21f3d1e06 Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Fri, 21 Apr 2023 23:20:23 +0200 Subject: [PATCH] Remove boilerplate errors --- src/api/auth/register.rs | 52 +++++++++++++++++++--- src/api/policies/instance/instance.rs | 10 ++--- src/api/schemas.rs | 36 ++++++++------- src/errors.rs | 14 +++--- src/instance.rs | 63 +++++++-------------------- 5 files changed, 87 insertions(+), 88 deletions(-) diff --git a/src/api/auth/register.rs b/src/api/auth/register.rs index 282614b..943a5c9 100644 --- a/src/api/auth/register.rs +++ b/src/api/auth/register.rs @@ -1,5 +1,4 @@ pub mod register { - use custom_error::custom_error; use reqwest::Client; use serde_json::json; @@ -31,12 +30,51 @@ pub mod register { .await; if response.is_none() { return Err(InstanceServerError::NoResponse); - } - let token = match response.unwrap().text().await { - Ok(token) => token, - Err(_) => return Err(InstanceServerError::NoResponse), - }; - return Ok(Token { token }); + } else { + // temp + return Err(InstanceServerError::NoResponse); + } // end temp + + /* + Things to do: + 1. Check the response for Errors. If the Response says the request is missing a field, + return an Err() that says that. + + */ } } } + +#[cfg(test)] +mod test { + use crate::api::schemas::schemas::RegisterSchema; + use crate::instance::Instance; + use crate::limit::LimitedRequester; + use crate::URLBundle; + #[tokio::test] + async fn test_registration() { + let urls = URLBundle::new( + "http://localhost:3001/api".to_string(), + "http://localhost:3001".to_string(), + "http://localhost:3001".to_string(), + ); + let limited_requester = LimitedRequester::new(urls.get_api().to_string()).await; + let mut test_instance = Instance::new(urls.clone(), limited_requester) + .await + .unwrap(); + let reg = RegisterSchema::new( + "Test".to_string(), + None, + true, + Some("me@mail.xy".to_string()), + None, + None, + None, + None, + None, + None, + ) + .unwrap(); + println!("{}", test_instance.register(®).await.unwrap()); + } +} diff --git a/src/api/policies/instance/instance.rs b/src/api/policies/instance/instance.rs index f0af029..2eaac5b 100644 --- a/src/api/policies/instance/instance.rs +++ b/src/api/policies/instance/instance.rs @@ -2,24 +2,24 @@ pub mod instance { use reqwest::Client; use serde_json::from_str; - use crate::errors::InstancePoliciesError; + use crate::errors::InstanceServerError; use crate::{api::schemas::schemas::InstancePoliciesSchema, instance::Instance}; impl Instance { /** Gets the instance policies schema. # Errors - [`InstancePoliciesError`] - If the request fails. + [`InstanceServerError`] - If the request fails. */ pub async fn instance_policies_schema( &self, - ) -> Result { + ) -> Result { let client = Client::new(); let endpoint_url = self.urls.get_api().to_string() + "/policies/instance/"; let request = match client.get(&endpoint_url).send().await { Ok(result) => result, Err(e) => { - return Err(InstancePoliciesError::RequestErrorError { + return Err(InstanceServerError::RequestErrorError { url: endpoint_url, error: e.to_string(), }); @@ -27,7 +27,7 @@ pub mod instance { }; if request.status().as_str().chars().next().unwrap() != '2' { - return Err(InstancePoliciesError::ReceivedErrorCodeError { + return Err(InstanceServerError::ReceivedErrorCodeError { error_code: request.status().to_string(), }); } diff --git a/src/api/schemas.rs b/src/api/schemas.rs index 680d074..d2a7ccc 100644 --- a/src/api/schemas.rs +++ b/src/api/schemas.rs @@ -1,11 +1,9 @@ pub mod schemas { - use std::fmt; - - use custom_error::custom_error; use regex::Regex; use serde::{Deserialize, Serialize}; + use std::fmt; - use crate::errors::RegisterSchemaError; + use crate::errors::FieldFormatError; #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] @@ -24,12 +22,12 @@ pub mod schemas { impl RegisterSchema { /** - Returns a new [`Result`]. + Returns a new [`Result`]. ## Arguments All but "String::username" and "bool::consent" are optional. ## Errors - You will receive a [`RegisterSchemaError`], if: + You will receive a [`FieldFormatError`], if: - The username is less than 2 or more than 32 characters in length - You supply a `password` which is less than 1 or more than 72 characters in length. @@ -46,22 +44,22 @@ pub mod schemas { gift_code_sku_id: Option, captcha_key: Option, promotional_email_opt_in: Option, - ) -> Result { + ) -> Result { if username.len() < 2 || username.len() > 32 { - return Err(RegisterSchemaError::UsernameError); + return Err(FieldFormatError::UsernameError); } if password.is_some() && (password.as_ref().unwrap().len() < 1 || password.as_ref().unwrap().len() > 72) { - return Err(RegisterSchemaError::PasswordError); + return Err(FieldFormatError::PasswordError); } if !consent { - return Err(RegisterSchemaError::ConsentError); + return Err(FieldFormatError::ConsentError); } let regex = Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap(); if email.clone().is_some() && !regex.is_match(email.clone().unwrap().as_str()) { - return Err(RegisterSchemaError::EmailError); + return Err(FieldFormatError::EmailError); } return Ok(RegisterSchema { @@ -159,7 +157,7 @@ pub mod schemas { #[cfg(test)] mod schemas_tests { use super::schemas::*; - use crate::errors::RegisterSchemaError; + use crate::errors::FieldFormatError; #[test] fn password_too_short() { @@ -176,7 +174,7 @@ mod schemas_tests { None, None, ), - Err(RegisterSchemaError::PasswordError) + Err(FieldFormatError::PasswordError) ); } @@ -199,7 +197,7 @@ mod schemas_tests { None, None, ), - Err(RegisterSchemaError::PasswordError) + Err(FieldFormatError::PasswordError) ); } @@ -218,7 +216,7 @@ mod schemas_tests { None, None, ), - Err(RegisterSchemaError::UsernameError) + Err(FieldFormatError::UsernameError) ); } @@ -230,7 +228,7 @@ mod schemas_tests { } assert_eq!( RegisterSchema::new(long_un, None, true, None, None, None, None, None, None, None,), - Err(RegisterSchemaError::UsernameError) + Err(FieldFormatError::UsernameError) ); } @@ -249,7 +247,7 @@ mod schemas_tests { None, None, ), - Err(RegisterSchemaError::ConsentError) + Err(FieldFormatError::ConsentError) ); } @@ -268,7 +266,7 @@ mod schemas_tests { None, None, ), - Err(RegisterSchemaError::EmailError) + Err(FieldFormatError::EmailError) ) } @@ -286,6 +284,6 @@ mod schemas_tests { None, None, ); - assert_ne!(reg, Err(RegisterSchemaError::EmailError)); + assert_ne!(reg, Err(FieldFormatError::EmailError)); } } diff --git a/src/errors.rs b/src/errors.rs index 438cd1d..0b54704 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -2,14 +2,7 @@ use custom_error::custom_error; custom_error! { #[derive(PartialEq, Eq)] - pub InstancePoliciesError - RequestErrorError{url:String, error:String} = "An error occured while trying to GET from {url}: {error}", - ReceivedErrorCodeError{error_code:String} = "Received the following error code while requesting from the route: {error_code}" -} - -custom_error! { - #[derive(PartialEq, Eq)] - pub RegisterSchemaError + pub FieldFormatError PasswordError = "Password must be between 1 and 72 characters.", UsernameError = "Username must be between 2 and 32 characters.", ConsentError = "Consent must be 'true' to register.", @@ -19,5 +12,8 @@ custom_error! { custom_error! { #[derive(PartialEq, Eq)] pub InstanceServerError - NoResponse = "Did not receive a response from the Server." + NoResponse = "Did not receive a response from the Server.", + RequestErrorError{url:String, error:String} = "An error occured while trying to GET from {url}: {error}", + ReceivedErrorCodeError{error_code:String} = "Received the following error code while requesting from the route: {error_code}", + CantGetInfoError{error:String} = "Something seems to be wrong with the instance. Cannot get information about the instance: {error}" } diff --git a/src/instance.rs b/src/instance.rs index db1502d..a655735 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -1,8 +1,5 @@ -use regex::internal::Inst; - -use crate::api::instance; use crate::api::schemas::schemas::InstancePoliciesSchema; -use crate::gateway::Gateway; +use crate::errors::{FieldFormatError, InstanceServerError}; use crate::limit::LimitedRequester; use crate::URLBundle; @@ -31,7 +28,7 @@ impl Instance { pub async fn new( urls: URLBundle, requester: LimitedRequester, - ) -> Result { + ) -> Result { let users: HashMap = HashMap::new(); let mut instance = Instance { urls, @@ -51,36 +48,27 @@ impl Instance { }; instance.instance_info = match instance.instance_policies_schema().await { Ok(schema) => schema, - Err(e) => return Err(InstanceError{message: format!("Something seems to be wrong with the instance. Cannot get information about the instance: {}", e)}), + Err(e) => { + return Err(InstanceServerError::CantGetInfoError { + error: e.to_string(), + }) + } }; Ok(instance) } } -#[derive(Debug, PartialEq, Eq)] -pub struct InstanceError { - pub message: String, -} - -impl InstanceError { - fn new(message: String) -> Self { - InstanceError { message } - } -} - -impl fmt::Display for InstanceError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.message) - } -} - -impl std::error::Error for InstanceError {} - #[derive(Debug, PartialEq, Eq)] pub struct Token { pub token: String, } +impl fmt::Display for Token { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.token) + } +} + #[derive(Debug, PartialEq, Eq)] pub struct Username { pub username: String, @@ -92,31 +80,10 @@ impl Username { /// * `username` - The username that will be used to create the [`Username`]. /// # Errors /// * [`UsernameFormatError`] - If the username is not between 2 and 32 characters. - pub fn new(username: String) -> Result { + pub fn new(username: String) -> Result { if username.len() < 2 || username.len() > 32 { - return Err(UsernameFormatError::new( - "Username must be between 2 and 32 characters".to_string(), - )); + return Err(FieldFormatError::UsernameError); } return Ok(Username { username }); } } - -#[derive(Debug, PartialEq, Eq)] -pub struct UsernameFormatError { - pub message: String, -} - -impl UsernameFormatError { - fn new(message: String) -> Self { - UsernameFormatError { message } - } -} - -impl fmt::Display for UsernameFormatError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.message) - } -} - -impl std::error::Error for UsernameFormatError {}