lemmy/lemmy_db/src/views/user_view.rs

72 lines
1.8 KiB
Rust
Raw Normal View History

2020-12-03 03:39:31 +00:00
use crate::{
2020-12-03 18:39:56 +00:00
aggregates::user_aggregates::UserAggregates,
schema::{user_, user_aggregates},
2020-12-03 03:39:31 +00:00
user::{UserSafe, User_},
};
use diesel::{result::Error, *};
use serde::Serialize;
#[derive(Debug, Serialize, Clone)]
pub struct UserViewSafe {
pub user: UserSafe,
2020-12-03 18:39:56 +00:00
pub counts: UserAggregates,
2020-12-03 03:39:31 +00:00
}
2020-12-03 18:39:56 +00:00
#[derive(Debug, Serialize, Clone)]
2020-12-03 03:39:31 +00:00
pub struct UserViewDangerous {
pub user: User_,
2020-12-03 18:39:56 +00:00
pub counts: UserAggregates,
2020-12-03 03:39:31 +00:00
}
impl UserViewDangerous {
pub fn read(conn: &PgConnection, id: i32) -> Result<Self, Error> {
2020-12-03 18:39:56 +00:00
let (user, counts) = user_::table
.find(id)
.inner_join(user_aggregates::table)
.first::<(User_, UserAggregates)>(conn)?;
Ok(Self { user, counts })
2020-12-03 03:39:31 +00:00
}
}
impl UserViewSafe {
pub fn read(conn: &PgConnection, id: i32) -> Result<Self, Error> {
2020-12-03 18:39:56 +00:00
let (user, counts) = user_::table
.find(id)
.inner_join(user_aggregates::table)
.first::<(User_, UserAggregates)>(conn)?;
Ok(Self {
user: user.to_safe(),
counts,
})
2020-12-03 03:39:31 +00:00
}
pub fn admins(conn: &PgConnection) -> Result<Vec<Self>, Error> {
let admins = user_::table
2020-12-03 18:39:56 +00:00
.inner_join(user_aggregates::table)
2020-12-03 03:39:31 +00:00
.filter(user_::admin.eq(true))
.order_by(user_::published)
2020-12-03 18:39:56 +00:00
.load::<(User_, UserAggregates)>(conn)?;
2020-12-03 03:39:31 +00:00
Ok(vec_to_user_view_safe(admins))
}
pub fn banned(conn: &PgConnection) -> Result<Vec<Self>, Error> {
let banned = user_::table
2020-12-03 18:39:56 +00:00
.inner_join(user_aggregates::table)
2020-12-03 03:39:31 +00:00
.filter(user_::banned.eq(true))
2020-12-03 18:39:56 +00:00
.load::<(User_, UserAggregates)>(conn)?;
2020-12-03 03:39:31 +00:00
Ok(vec_to_user_view_safe(banned))
}
}
2020-12-03 18:39:56 +00:00
fn vec_to_user_view_safe(users: Vec<(User_, UserAggregates)>) -> Vec<UserViewSafe> {
2020-12-03 03:39:31 +00:00
users
.iter()
2020-12-03 18:39:56 +00:00
.map(|a| UserViewSafe {
user: a.0.to_safe(),
counts: a.1.to_owned(),
})
2020-12-03 03:39:31 +00:00
.collect::<Vec<UserViewSafe>>()
}