Skip to main content

max / makenotwork

1.8 KB · 73 lines History Blame Raw
1 //! membership and role reads for one community
2
3 use super::{CommunityRole, DateTime, PgPool, Utc, Uuid};
4
5 #[tracing::instrument(skip_all)]
6 pub async fn get_user_role(
7 pool: &PgPool,
8 user_id: Uuid,
9 community_id: Uuid,
10 ) -> Result<Option<CommunityRole>, sqlx::Error> {
11 sqlx::query_scalar!(
12 r#"SELECT role AS "role: CommunityRole" FROM memberships WHERE user_id = $1 AND community_id = $2"#,
13 user_id,
14 community_id,
15 )
16 .fetch_optional(pool)
17 .await
18 }
19
20 #[derive(sqlx::FromRow)]
21 pub struct MemberRow {
22 pub username: String,
23 pub display_name: Option<String>,
24 pub role: CommunityRole,
25 pub joined_at: DateTime<Utc>,
26 }
27
28 #[tracing::instrument(skip_all)]
29 pub async fn list_community_members(
30 pool: &PgPool,
31 community_id: Uuid,
32 limit: i64,
33 offset: i64,
34 ) -> Result<Vec<MemberRow>, sqlx::Error> {
35 sqlx::query_as!(
36 MemberRow,
37 r#"SELECT u.username,
38 u.display_name,
39 m.role AS "role: CommunityRole",
40 m.joined_at AS "joined_at: chrono::DateTime<chrono::Utc>"
41 FROM memberships m
42 JOIN users u ON u.mnw_account_id = m.user_id
43 WHERE m.community_id = $1
44 ORDER BY
45 CASE m.role
46 WHEN 'owner' THEN 0
47 WHEN 'moderator' THEN 1
48 WHEN 'member' THEN 2
49 END,
50 m.joined_at
51 LIMIT $2 OFFSET $3"#,
52 community_id,
53 limit,
54 offset,
55 )
56 .fetch_all(pool)
57 .await
58 }
59
60 /// Count members in a community.
61 #[tracing::instrument(skip_all)]
62 pub async fn count_community_members(
63 pool: &PgPool,
64 community_id: Uuid,
65 ) -> Result<i64, sqlx::Error> {
66 sqlx::query_scalar!(
67 r#"SELECT COUNT(*) AS "count!" FROM memberships WHERE community_id = $1"#,
68 community_id,
69 )
70 .fetch_one(pool)
71 .await
72 }
73