70 lines
2.3 KiB
Rust
70 lines
2.3 KiB
Rust
use crate::models::{role, role_user};
|
|
use crate::repositories::{AnyResult, RepositoryContext};
|
|
use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, QueryFilter, Set};
|
|
use std::sync::Arc;
|
|
use uuid::Uuid;
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct RoleRepository {
|
|
pub context: Arc<RepositoryContext>,
|
|
}
|
|
|
|
impl RoleRepository {
|
|
pub async fn get_all_by_server(&self, server_id: Uuid) -> AnyResult<Vec<role::Model>> {
|
|
Ok(role::Entity::find()
|
|
.filter(role::Column::ServerId.eq(server_id))
|
|
.all(&self.context.db)
|
|
.await?)
|
|
}
|
|
|
|
pub async fn get_default_by_server(&self, server_id: Uuid) -> AnyResult<Option<role::Model>> {
|
|
Ok(role::Entity::find()
|
|
.filter(role::Column::ServerId.eq(server_id))
|
|
.filter(role::Column::IsDefault.eq(true))
|
|
.one(&self.context.db)
|
|
.await?)
|
|
}
|
|
|
|
pub async fn add_to_default(&self, user_id: Uuid, server_id: Uuid) -> AnyResult<()> {
|
|
let default_role = self.get_default_by_server(server_id).await?;
|
|
if let Some(default_role) = default_role {
|
|
role_user::ActiveModel {
|
|
role_id: Set(default_role.id),
|
|
user_id: Set(user_id),
|
|
..Default::default()
|
|
}
|
|
.insert(&self.context.db)
|
|
.await?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub async fn get_all(&self) -> AnyResult<Vec<role::Model>> {
|
|
Ok(role::Entity::find().all(&self.context.db).await?)
|
|
}
|
|
|
|
pub async fn get_by_id(&self, id: Uuid) -> AnyResult<Option<role::Model>> {
|
|
Ok(role::Entity::find_by_id(id).one(&self.context.db).await?)
|
|
}
|
|
|
|
pub async fn create(&self, active: role::ActiveModel) -> AnyResult<role::Model> {
|
|
let group = active.insert(&self.context.db).await?;
|
|
self.context.events.emit("group_created", group.clone());
|
|
Ok(group)
|
|
}
|
|
|
|
pub async fn update(&self, active: role::ActiveModel) -> AnyResult<role::Model> {
|
|
let group = active.update(&self.context.db).await?;
|
|
self.context.events.emit("group_updated", group.clone());
|
|
Ok(group)
|
|
}
|
|
|
|
pub async fn delete(&self, id: Uuid) -> AnyResult<bool> {
|
|
let res = role::Entity::delete_by_id(id)
|
|
.exec(&self.context.db)
|
|
.await?;
|
|
self.context.events.emit("group_deleted", id);
|
|
Ok(res.rows_affected > 0)
|
|
}
|
|
}
|