use serde::Serialize; use warp::{reject::Reject, Rejection}; use crate::database::{ db, users::{self, UserSelect, Users}, }; #[derive(Clone)] pub struct Profiler { db: Users, } impl Profiler { pub fn new(db: Users) -> Self { Self { db } } pub async fn profile(&self, username: String) -> Result { let select = if username.contains("@") { UserSelect::FullUsername(username) } else { UserSelect::Username(username) }; match self.db.user(select).await? { Some(user) => Ok(User::from(user)), None => Err(UserError::NotFound), } } pub async fn create_user( &self, username: String, display_name: Option, ) -> Result { let result = self .db .create_user( User { id: String::new(), username, display_name, host: None, } .into(), ) .await?; Ok(User::from(result)) } } #[derive(Clone, Debug, Serialize)] pub struct User { pub id: String, pub username: String, pub display_name: Option, pub host: Option, } impl From for User { fn from(u: users::User) -> Self { Self { id: u.id, username: u.username, display_name: u.display_name, host: u.host, } } } impl Into for User { fn into(self) -> users::User { users::User { id: self.id, username: self.username, display_name: self.display_name, host: self.host, } } } #[derive(Debug, Clone)] pub enum UserError { Duplicate, NotFound, Other(String), } impl From for UserError { fn from(err: anyhow::Error) -> Self { Self::Other(format!("UserError: {}", err)) } } impl From for UserError { fn from(err: db::DBError) -> Self { match err { db::DBError::Duplicate => Self::Duplicate, db::DBError::Other(e) => Self::Other(e.to_string()), } } } impl ToString for UserError { fn to_string(&self) -> String { match self { Self::Duplicate => String::from("duplicate insert"), Self::NotFound => String::from("not found"), Self::Other(err) => err.clone(), } } } impl Reject for UserError {}