aboutsummaryrefslogtreecommitdiff
path: root/src/util.rs
blob: 1d930850b9b78256da39823e62e3ef5a48a2d023 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
use entity::{invite_tokens, queues, users};
use sea_orm::{ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter};

use crate::{ApiError, ClientError};

pub async fn user_exists(id: i64, db: &DatabaseConnection) -> Result<bool, ApiError> {
    Ok(users::Entity::find_by_id(id).one(db).await?.is_some())
}

pub async fn username_exists(username: &str, db: &DatabaseConnection) -> Result<bool, ApiError> {
    Ok(users::Entity::find()
        .filter(users::Column::Username.eq(username))
        .one(db)
        .await?
        .is_some())
}

pub async fn get_owned_queue(
    id: i64,
    owner_id: i64,
    db: &DatabaseConnection,
) -> Result<queues::Model, ApiError> {
    let queue = queues::Entity::find_by_id(id)
        .one(db)
        .await?
        .ok_or(ClientError::QueueNotFound { id })?;

    if queue.owner_id != owner_id {
        return Err(ClientError::NotQueueOwner { id: queue.id }.into());
    }

    Ok(queue)
}

pub async fn get_owned_invite_token(
    id: i64,
    owner_id: i64,
    db: &DatabaseConnection,
) -> Result<invite_tokens::Model, ApiError> {
    let (invite_token, queue) = invite_tokens::Entity::find_by_id(id)
        .find_also_related(queues::Entity)
        .one(db)
        .await?
        .ok_or(ClientError::InviteTokenNotFound { id })?;

    if queue.unwrap().owner_id != owner_id {
        return Err(ClientError::NoInviteTokenAccess { id }.into());
    }

    Ok(invite_token)
}