From 1b9ccf31544fcac1acfdee313ad2cdda9a498498 Mon Sep 17 00:00:00 2001 From: bitfl0wer Date: Sat, 15 Apr 2023 22:06:18 +0200 Subject: [PATCH] add "new" method for RegSchema with custom errors --- src/api/schemas.rs | 74 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/src/api/schemas.rs b/src/api/schemas.rs index 08634e9..bb5c08b 100644 --- a/src/api/schemas.rs +++ b/src/api/schemas.rs @@ -1,4 +1,7 @@ pub mod schemas { + use std::error::Error; + use std::fmt; + use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] @@ -16,6 +19,77 @@ pub mod schemas { promotional_email_opt_in: Option, } + #[derive(Debug)] + pub struct RegisterSchemaError { + message: String, + } + + impl RegisterSchemaError { + fn new(message: String) -> Self { + RegisterSchemaError { message } + } + } + + impl fmt::Display for RegisterSchemaError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.message) + } + } + + impl std::error::Error for RegisterSchemaError {} + + impl RegisterSchema { + /** + Returns a new [`Result`]. + ## Arguments + All but "String::username" and "bool::consent" are optional. + + ## Errors + You will receive a [`RegisterSchemaError`], 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. + + These constraints have been defined [in the Spacebar-API](https://docs.spacebar.chat/routes/) + */ + pub fn new( + username: String, + password: Option, + consent: bool, + email: Option, + fingerprint: Option, + invite: Option, + date_of_birth: Option, + gift_code_sku_id: Option, + captcha_key: Option, + promotional_email_opt_in: Option, + ) -> Result { + if username.len() < 2 || username.len() > 32 { + return Err(RegisterSchemaError::new( + "Username must be between 2 and 32 characters".to_string(), + )); + } + if password.is_some() + && (password.as_ref().unwrap().len() < 1 || password.as_ref().unwrap().len() > 72) + { + return Err(RegisterSchemaError { + message: "Password must be between 1 and 72 characters.".to_string(), + }); + } + return Ok(RegisterSchema { + username, + password, + consent, + email, + fingerprint, + invite, + date_of_birth, + gift_code_sku_id, + captcha_key, + promotional_email_opt_in, + }); + } + } + #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct LoginSchema {