lemmy/lemmy_db/src/views/community_view.rs

60 lines
1.5 KiB
Rust
Raw Normal View History

2020-12-04 16:29:44 +00:00
use crate::{
2020-12-04 21:35:46 +00:00
aggregates::community_aggregates::CommunityAggregates,
2020-12-04 16:29:44 +00:00
category::Category,
community::{Community, CommunityFollower},
2020-12-04 21:35:46 +00:00
schema::{category, community, community_aggregates, community_follower, user_},
2020-12-04 16:29:44 +00:00
user::{UserSafe, User_},
2020-12-05 04:18:30 +00:00
ToSafe,
2020-12-04 16:29:44 +00:00
};
use diesel::{result::Error, *};
use serde::Serialize;
#[derive(Debug, Serialize, Clone)]
pub struct CommunityView {
pub community: Community,
pub creator: UserSafe,
pub category: Category,
pub subscribed: bool,
2020-12-04 21:35:46 +00:00
pub counts: CommunityAggregates,
2020-12-04 16:29:44 +00:00
}
impl CommunityView {
pub fn read(
conn: &PgConnection,
community_id: i32,
my_user_id: Option<i32>,
) -> Result<Self, Error> {
let subscribed = match my_user_id {
Some(user_id) => {
let res = community_follower::table
.filter(community_follower::community_id.eq(community_id))
.filter(community_follower::user_id.eq(user_id))
.get_result::<CommunityFollower>(conn);
res.is_ok()
}
None => false,
};
2020-12-04 21:35:46 +00:00
let (community, creator, category, counts) = community::table
2020-12-04 16:29:44 +00:00
.find(community_id)
.inner_join(user_::table)
.inner_join(category::table)
2020-12-04 21:35:46 +00:00
.inner_join(community_aggregates::table)
2020-12-05 04:18:30 +00:00
.select((
community::all_columns,
User_::safe_columns_tuple(),
category::all_columns,
community_aggregates::all_columns,
))
.first::<(Community, UserSafe, Category, CommunityAggregates)>(conn)?;
2020-12-04 16:29:44 +00:00
Ok(CommunityView {
community,
2020-12-05 04:18:30 +00:00
creator,
2020-12-04 16:29:44 +00:00
category,
subscribed,
2020-12-04 21:35:46 +00:00
counts,
2020-12-04 16:29:44 +00:00
})
}
}