magnetar/ext_calckey_model/src/lib.rs

64 lines
1.7 KiB
Rust
Raw Normal View History

use ck::user;
use sea_orm::{ColumnTrait, ConnectOptions, DatabaseConnection, EntityTrait, QueryFilter};
2023-07-07 19:22:30 +00:00
use thiserror::Error;
use tracing::log::LevelFilter;
#[derive(Debug)]
pub struct ConnectorConfig {
pub url: String,
}
#[derive(Clone, Debug)]
pub struct CalckeyModel(DatabaseConnection);
2023-07-07 19:22:30 +00:00
#[derive(Debug, Error)]
pub enum CalckeyDbError {
#[error("Database error: {0}")]
DbError(#[from] sea_orm::DbErr),
}
impl CalckeyModel {
2023-07-07 19:22:30 +00:00
pub async fn new(config: ConnectorConfig) -> Result<Self, CalckeyDbError> {
let opt = ConnectOptions::new(config.url)
.max_connections(64)
.min_connections(8)
.sqlx_logging(true)
.sqlx_logging_level(LevelFilter::Debug)
.to_owned();
Ok(CalckeyModel(sea_orm::Database::connect(opt).await?))
}
pub async fn get_user_by_tag(
&self,
name: &str,
instance: Option<&str>,
2023-07-07 19:22:30 +00:00
) -> Result<Option<user::Model>, CalckeyDbError> {
let name = name.to_lowercase();
let instance = instance.map(str::to_lowercase);
let user = if let Some(instance) = instance {
user::Entity::find()
.filter(user::Column::UsernameLower.eq(name))
.filter(user::Column::Host.eq(instance))
} else {
2023-04-22 00:37:18 +00:00
user::Entity::find().filter(
user::Column::UsernameLower
.eq(name)
.and(user::Column::Host.is_null()),
)
}
.one(&self.0)
.await?;
Ok(user)
}
2023-07-07 19:22:30 +00:00
pub async fn get_user_by_uri(&self, uri: &str) -> Result<Option<user::Model>, CalckeyDbError> {
Ok(user::Entity::find()
.filter(user::Column::Uri.eq(uri))
.one(&self.0)
.await?)
}
}