summaryrefslogtreecommitdiff
path: root/src/channel/routes.rs
blob: 4453a1e17e535b7457902e7ef612cdb0f1c49c14 (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
use axum::{
    extract::{Form, Path, State},
    response::{IntoResponse, Redirect},
    routing::post,
    Router,
};
use sqlx::sqlite::SqlitePool;

use super::repo::{Id as ChannelId, Provider as _};
use crate::{error::InternalError, login::repo::logins::Login};

pub fn router() -> Router<SqlitePool> {
    Router::new()
        .route("/create", post(on_create))
        .route("/:channel/leave", post(on_leave))
}

#[derive(serde::Deserialize)]
struct CreateRequest {
    name: String,
}

async fn on_create(
    State(db): State<SqlitePool>,
    login: Login,
    Form(form): Form<CreateRequest>,
) -> Result<impl IntoResponse, InternalError> {
    let mut tx = db.begin().await?;
    let channel = tx.channels().create(&form.name).await?;
    tx.channels().join(&channel.id, &login.id).await?;
    tx.commit().await?;

    Ok(Redirect::to("/"))
}

async fn on_leave(
    State(db): State<SqlitePool>,
    login: Login,
    Path(channel): Path<ChannelId>,
) -> Result<impl IntoResponse, InternalError> {
    let mut tx = db.begin().await?;
    tx.channels().leave(&channel, &login.id).await?;
    tx.commit().await?;

    Ok(Redirect::to("/"))
}