summaryrefslogtreecommitdiff
path: root/src/conversation/handlers/create/mod.rs
blob: aa77411118776d91dd9a7ab53d0a32a9697210ad (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
60
61
62
63
use axum::{
    extract::{Json, State},
    http::StatusCode,
    response::{self, IntoResponse},
};

use crate::{
    clock::RequestedAt,
    conversation::{Conversation, app, app::Conversations},
    error::Internal,
    name::Name,
    token::extract::Identity,
};

#[cfg(test)]
mod test;

pub async fn handler(
    State(conversations): State<Conversations>,
    _: Identity, // requires auth, but doesn't actually care who you are
    RequestedAt(created_at): RequestedAt,
    Json(request): Json<Request>,
) -> Result<Response, Error> {
    let conversation = conversations
        .create(&request.name, &created_at)
        .await
        .map_err(Error)?;

    Ok(Response(conversation))
}

#[derive(serde::Deserialize)]
pub struct Request {
    pub name: Name,
}

#[derive(Debug)]
pub struct Response(pub Conversation);

impl IntoResponse for Response {
    fn into_response(self) -> response::Response {
        let Self(conversation) = self;
        (StatusCode::ACCEPTED, Json(conversation)).into_response()
    }
}

#[derive(Debug)]
pub struct Error(pub app::CreateError);

impl IntoResponse for Error {
    fn into_response(self) -> response::Response {
        let Self(error) = self;
        match error {
            app::CreateError::DuplicateName(_) => {
                (StatusCode::CONFLICT, error.to_string()).into_response()
            }
            app::CreateError::InvalidName(_) => {
                (StatusCode::BAD_REQUEST, error.to_string()).into_response()
            }
            app::CreateError::Failed(_) => Internal::from(error).into_response(),
        }
    }
}