47 lines
1.2 KiB
Rust
47 lines
1.2 KiB
Rust
use eyre::Result;
|
|
use foxchat::{FoxError, Id, id::{ChannelType, GuildType}};
|
|
use sqlx::PgExecutor;
|
|
use ulid::Ulid;
|
|
|
|
pub struct Channel {
|
|
pub id: Id<ChannelType>,
|
|
pub guild_id: Id<GuildType>,
|
|
pub name: String,
|
|
pub topic: Option<String>,
|
|
}
|
|
|
|
pub async fn create_channel(
|
|
executor: impl PgExecutor<'_>,
|
|
guild_id: &Id<GuildType>,
|
|
name: &str,
|
|
topic: Option<String>,
|
|
) -> Result<Channel> {
|
|
let channel = sqlx::query_as!(
|
|
Channel,
|
|
"insert into channels (id, guild_id, name, topic) values ($1, $2, $3, $4) returning *",
|
|
Ulid::new().to_string(),
|
|
guild_id.0,
|
|
name,
|
|
topic
|
|
)
|
|
.fetch_one(executor)
|
|
.await?;
|
|
|
|
Ok(channel)
|
|
}
|
|
|
|
pub async fn get_channel(executor: impl PgExecutor<'_>, channel_id: &Id<ChannelType>) -> Result<Channel, FoxError> {
|
|
let channel = sqlx::query_as!(Channel, "select * from channels where id = $1", channel_id.0)
|
|
.fetch_one(executor)
|
|
.await
|
|
.map_err(|e| match e {
|
|
sqlx::Error::RowNotFound => FoxError::NotInGuild,
|
|
_ => {
|
|
tracing::error!("database error: {}", e);
|
|
|
|
return FoxError::DatabaseError;
|
|
}
|
|
})?;
|
|
|
|
Ok(channel)
|
|
}
|