Skip to main content

openlegends_server/api/user/register/request/
data.rs

1pub mod error;
2pub use error::Error;
3
4pub const USERNAME_PATTERN: &str = r"^[\w]{2,64}$";
5
6use regex::Regex;
7use serde::{Deserialize, Serialize};
8
9#[derive(Serialize, Deserialize, Debug)]
10pub struct Data {
11    username: String,
12}
13
14impl Data {
15    pub fn build(username: String) -> Result<Self, Error> {
16        match Regex::new(USERNAME_PATTERN) {
17            Ok(regex) => {
18                if regex.is_match(&username) {
19                    Ok(Self { username })
20                } else {
21                    Err(Error::Username(USERNAME_PATTERN.to_string()))
22                }
23            }
24            Err(e) => Err(Error::Regex(e)),
25        }
26    }
27
28    pub fn to_json(&self) -> Result<String, Error> {
29        match serde_json::to_string(&self) {
30            Ok(json) => Ok(json),
31            Err(e) => Err(Error::Json(e)),
32        }
33    }
34
35    pub fn username(&self) -> &str {
36        &self.username
37    }
38}