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
60
61
62
63
64
|
use sqlx::sqlite::SqlitePool;
use crate::{
events::broadcaster::Broadcaster,
repo::channel::{Channel, Provider as _},
};
pub struct Channels<'a> {
db: &'a SqlitePool,
broadcaster: &'a Broadcaster,
}
impl<'a> Channels<'a> {
pub const fn new(db: &'a SqlitePool, broadcaster: &'a Broadcaster) -> Self {
Self { db, broadcaster }
}
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))?;
self.broadcaster.register_channel(&channel.id);
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),
}
|