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