summaryrefslogtreecommitdiff
path: root/src/channel/app.rs
blob: 6bad1589d139b97adcb94bbc5f3c5a65ffd3a172 (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
52
53
54
55
56
57
58
59
use sqlx::sqlite::SqlitePool;

use crate::repo::channel::{Channel, Provider as _};

pub struct Channels<'a> {
    db: &'a SqlitePool,
}

impl<'a> Channels<'a> {
    pub const fn new(db: &'a SqlitePool) -> Self {
        Self { db }
    }

    pub async fn create(&self, name: &str) -> Result<Channel, CreateError> {
        let mut tx = self.db.begin().await?;
        let channel = tx
            .channels()
            .create(name)
            .await
            .map_err(|err| CreateError::from_duplicate_name(err, name))?;
        tx.commit().await?;

        Ok(channel)
    }

    pub async fn all(&self) -> Result<Vec<Channel>, InternalError> {
        let mut tx = self.db.begin().await?;
        let channels = tx.channels().all().await?;
        tx.commit().await?;

        Ok(channels)
    }
}

#[derive(Debug, thiserror::Error)]
pub enum CreateError {
    #[error("channel named {0} already exists")]
    DuplicateName(String),
    #[error(transparent)]
    DatabaseError(#[from] sqlx::Error),
}

impl CreateError {
    fn from_duplicate_name(error: sqlx::Error, name: &str) -> Self {
        if let Some(error) = error.as_database_error() {
            if error.is_unique_violation() {
                return Self::DuplicateName(name.into());
            }
        }

        Self::from(error)
    }
}

#[derive(Debug, thiserror::Error)]
pub enum InternalError {
    #[error(transparent)]
    DatabaseError(#[from] sqlx::Error),
}