flabk/src/svc/profiles.rs

116 lines
2.5 KiB
Rust

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<User, UserError> {
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<String>,
) -> Result<User, UserError> {
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<String>,
pub host: Option<String>,
}
impl From<users::User> 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<users::User> 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<anyhow::Error> for UserError {
fn from(err: anyhow::Error) -> Self {
Self::Other(format!("UserError: {}", err))
}
}
impl From<db::DBError> 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 {}